Skip to content

Commit

Permalink
Parse \r and \r\n line endings (#414)
Browse files Browse the repository at this point in the history
* replace all EOLs to standard Unix EOL

* Tests all three types of EOL
  • Loading branch information
AlexanderGranhof authored and maxbeatty committed Aug 15, 2019
1 parent eba176b commit 52fe318
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,15 @@ function log (message /*: string */) {
const NEWLINE = '\n'
const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
const RE_NEWLINES = /\\n/g
const NEWLINES_MATCH = /\n|\r|\r\n/

This comment has been minimized.

Copy link
@felixmosh

felixmosh Aug 18, 2019

is it better to use shorter regex?
/\r?\n/

This comment has been minimized.

Copy link
@vrumger

vrumger Dec 1, 2019

That won't match only \r.


// Parses src into an Object
function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
const debug = Boolean(options && options.debug)
const obj = {}

// convert Buffers before splitting into lines and processing
src.toString().split(NEWLINE).forEach(function (line, idx) {
src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(RE_INI_KEY_VAL)
// matched?
Expand Down
13 changes: 12 additions & 1 deletion tests/test-parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const dotenv = require('../lib/main')

const parsed = dotenv.parse(fs.readFileSync('tests/.env', { encoding: 'utf8' }))

t.plan(24)
t.plan(27)

t.type(parsed, Object, 'should return an object')

Expand Down Expand Up @@ -58,6 +58,17 @@ t.equal(parsed.SPACED_KEY, 'parsed', 'parses keys and values surrounded by space
const payload = dotenv.parse(Buffer.from('BUFFER=true'))
t.equal(payload.BUFFER, 'true', 'should parse a buffer into an object')

const expectedPayload = { SERVER: 'localhost', PASSWORD: 'password', DB: 'tests' }

const RPayload = dotenv.parse(Buffer.from('SERVER=localhost\rPASSWORD=password\rDB=tests\r'))
t.same(RPayload, expectedPayload, 'can parse (\\r) line endings')

const NPayload = dotenv.parse(Buffer.from('SERVER=localhost\nPASSWORD=password\nDB=tests\n'))
t.same(NPayload, expectedPayload, 'can parse (\\n) line endings')

const RNPayload = dotenv.parse(Buffer.from('SERVER=localhost\r\nPASSWORD=password\r\nDB=tests\r\n'))
t.same(RNPayload, expectedPayload, 'can parse (\\r\\n) line endings')

// test debug path
const logStub = sinon.stub(console, 'log')
dotenv.parse(Buffer.from('what is this'), { debug: true })
Expand Down

0 comments on commit 52fe318

Please sign in to comment.