Skip to content

Commit e85159d

Browse files
committed
src: handle empty value without newline at EOF
1 parent a723280 commit e85159d

File tree

4 files changed

+29
-3
lines changed

4 files changed

+29
-3
lines changed

src/node_dotenv.cc

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#include "node_dotenv.h"
2-
#include <regex> // NOLINT(build/c++11)
32
#include <unordered_set>
43
#include "env-inl.h"
54
#include "node_file.h"
@@ -104,7 +103,12 @@ std::string_view trim_spaces(std::string_view input) {
104103
}
105104

106105
void Dotenv::ParseContent(const std::string_view input) {
107-
std::string_view content = input;
106+
std::string lines(input);
107+
108+
// Handle windows newlines "\r\n": remove "\r" and keep only "\n"
109+
lines.erase(std::remove(lines.begin(), lines.end(), '\r'), lines.end());
110+
111+
std::string_view content = lines;
108112
content = trim_spaces(content);
109113

110114
std::string_view key;
@@ -142,6 +146,9 @@ void Dotenv::ParseContent(const std::string_view input) {
142146

143147
// SAFETY: Content is guaranteed to have at least one character
144148
if (content.empty()) {
149+
// In case the last line is a single key without value
150+
// Example: KEY= (without a newline at the EOF)
151+
store_.insert_or_assign(std::string(key), "");
145152
break;
146153
}
147154

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
BASIC=value
2+
EMPTY=

test/fixtures/dotenv/multiline.env

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ LgGJQwu9WqyzHKZ6WIA5T+7zPjO1L8l3S8k8YzBrfH4mqWOD1GBI8Yjq2L1ac3Y/
44
bTdfHN8CmQr2iDJC0C6zY8YV93oZB3x0zC/LPbRYpF8f6OqX1lZj5vo2zJZy4fI/
55
kKcI5jHYc8VJq+KCuRZrvn+3V+KuL9tF9v8ZgjF2PZbU+LsCy5Yqg1M8f5Jp5f6V
66
u4QuUoobAgMBAAE=
7-
-----END PUBLIC KEY-----"
7+
-----END PUBLIC KEY-----"

test/parallel/test-dotenv-edge-cases.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,21 @@ describe('.env supports edge cases', () => {
8181
assert.strictEqual(child.stderr, '');
8282
assert.strictEqual(child.code, 0);
8383
});
84+
85+
it('should handle empty value without a newline at the EOF', async () => {
86+
// Ref: https://github.com/nodejs/node/issues/52466
87+
const code = `
88+
process.loadEnvFile('./eof-without-value.env');
89+
require('assert').strictEqual(process.env.BASIC, 'value');
90+
require('assert').strictEqual(process.env.EMPTY, '');
91+
`.trim();
92+
const child = await common.spawnPromisified(
93+
process.execPath,
94+
[ '--eval', code ],
95+
{ cwd: fixtures.path('dotenv') },
96+
);
97+
assert.strictEqual(child.stdout, '');
98+
assert.strictEqual(child.stderr, '');
99+
assert.strictEqual(child.code, 0);
100+
});
84101
});

0 commit comments

Comments
 (0)