Skip to content

Commit 97fa6a0

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

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

src/node_dotenv.cc

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,10 @@ std::string_view trim_spaces(std::string_view input) {
104104
}
105105

106106
void Dotenv::ParseContent(const std::string_view input) {
107-
std::string_view content = input;
107+
std::string lines =
108+
std::regex_replace(std::string(input), std::regex("\r\n?"), "\n");
109+
110+
std::string_view content = lines;
108111
content = trim_spaces(content);
109112

110113
std::string_view key;
@@ -142,6 +145,9 @@ void Dotenv::ParseContent(const std::string_view input) {
142145

143146
// SAFETY: Content is guaranteed to have at least one character
144147
if (content.empty()) {
148+
// In case the last line is a single key without value
149+
// Example: KEY= (without a newline at the EOF)
150+
store_.insert_or_assign(std::string(key), "");
145151
break;
146152
}
147153

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

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)