diff --git a/src/node_dotenv.cc b/src/node_dotenv.cc index d01538bd054ac6..59097806953ff8 100644 --- a/src/node_dotenv.cc +++ b/src/node_dotenv.cc @@ -142,6 +142,9 @@ void Dotenv::ParseContent(const std::string_view input) { // SAFETY: Content is guaranteed to have at least one character if (content.empty()) { + // In case the last line is a single key without value + // Example: KEY= (without a newline at the EOF) + store_.insert_or_assign(std::string(key), ""); break; } diff --git a/test/fixtures/dotenv/eof-without-value.env b/test/fixtures/dotenv/eof-without-value.env new file mode 100644 index 00000000000000..1806141cfa01ae --- /dev/null +++ b/test/fixtures/dotenv/eof-without-value.env @@ -0,0 +1,2 @@ +BASIC=value +EMPTY= \ No newline at end of file diff --git a/test/parallel/test-dotenv-edge-cases.js b/test/parallel/test-dotenv-edge-cases.js index 3a894270d9514e..f8cd262c8a8092 100644 --- a/test/parallel/test-dotenv-edge-cases.js +++ b/test/parallel/test-dotenv-edge-cases.js @@ -81,4 +81,21 @@ describe('.env supports edge cases', () => { assert.strictEqual(child.stderr, ''); assert.strictEqual(child.code, 0); }); + + it('should handle empty value without a newline at the EOF', async () => { + // Ref: https://github.com/nodejs/node/issues/52466 + const code = ` + process.loadEnvFile('./eof-without-value.env'); + require('assert').strictEqual(process.env.BASIC, 'value'); + require('assert').strictEqual(process.env.EMPTY, ''); + `.trim(); + const child = await common.spawnPromisified( + process.execPath, + [ '--eval', code ], + { cwd: fixtures.path('dotenv') }, + ); + assert.strictEqual(child.stdout, ''); + assert.strictEqual(child.stderr, ''); + assert.strictEqual(child.code, 0); + }); });