Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,22 @@ function parseFast (src) {
let j = vStart
while (j < len) {
const cc = str.charCodeAt(j)
if (cc === 92 /* \ */ && j + 1 < len && str.charCodeAt(j + 1) === quote) {
j += 2
} else if (cc === quote) {
// a backslash consumes the next character when it escapes the quote (\") or
// another backslash (\\). Without the \\ case the second backslash of a pair
// is left free to escape a following closing quote, so a value ending in an
// escaped backslash — VAR="C:\\dir\\" — runs past its own closing quote and
// swallows the rest of the file.
if (cc === 92 /* \ */ && j + 1 < len) {
const nc = str.charCodeAt(j + 1)
if (nc === quote || nc === 92 /* \ */) {
j += 2
continue
}
}
if (cc === quote) {
break
} else {
j++
}
j++
}
if (j >= len) {
// unterminated quote — fall back to unquoted-from-here semantics
Expand Down
28 changes: 28 additions & 0 deletions tests/test-parse-fast.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,34 @@ t.test('fast parse matches classic parse for a leading UTF-8 BOM', ct => {
ct.end()
})

t.test('fast parse matches classic parse for an escaped backslash before the closing quote', ct => {
const cases = [
'KEY="\\\\"',
'KEY="\\\\"\nNEXT=ok\n',
"KEY='\\\\'\nNEXT=ok\n",
'KEY=`\\\\`\nNEXT=ok\n',
'WINDIR="C:\\\\Users\\\\me\\\\"\nAPI_KEY=secret\nPORT=3000\n',
'KEY="a\\\\b"\nNEXT=ok\n',
'KEY="\\\\\\\\"\nNEXT=ok\n',
'A="\\\\"\nB=plain\nC="quoted"\nD=last\n'
]

for (const src of cases) {
assertSameParse(ct, src, JSON.stringify(src))
}

// pin the behaviour, so the two parsers can't agree by both being wrong.
// dotenv does not unescape \\, so the value keeps both backslashes — the point
// is that the value ends at its own closing quote and the later keys survive.
ct.same(dotenv.parse('A="\\\\"\nB=plain\nC="quoted"\nD=last\n', { fast: true }), {
A: '\\\\',
B: 'plain',
C: 'quoted',
D: 'last'
})
ct.end()
})

t.test('config({ fast: true }) reads a .env written with a BOM', ct => {
const processEnv = {}
const result = dotenv.config({
Expand Down
Loading