From 27cfacf028bd2d2cf999eedd00ce8bf4917ecf0c Mon Sep 17 00:00:00 2001 From: Becca Date: Tue, 28 Nov 2017 17:42:09 -0500 Subject: [PATCH] Return boolean values instead of "true"/"false" strings. When boolean values are set in an .env file (e.g. IS_PRODUCTION=false), it's expected that these will be evalulated as booleans, instead of the string "false" (which is truthy). This causes particular problems when using webpack and webpack.DefinePlugin, since providing `JSON.stringify(process.env.IS_PRODUCTION` will evaluate as a string, which is unexpected. Instead, change `"true"` to `true` and `"false"` to `false` when evaluating the .env file. --- README.md | 3 ++- lib/main.js | 7 +++++++ test/.env | 2 ++ test/main.js | 6 ++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d90f49a4..aa465be8 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ _Alias: `load`_ `config` will read your .env file, parse the contents, assign it to [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env), -and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed. +and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed. ```js const result = dotenv.config() @@ -135,6 +135,7 @@ line'} ``` - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`) - whitespace is removed from both ends of the value (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO=" some value "` becomes `{FOO: 'some value'}`) +- booleans are maintained (`TRUTHY_VALUE=true` becomes `{TRUTHY_VALUE: true}`) ## FAQ diff --git a/lib/main.js b/lib/main.js index ef74a7bc..46c97f38 100644 --- a/lib/main.js +++ b/lib/main.js @@ -30,6 +30,13 @@ function parse (src) { // remove any surrounding quotes and extra spaces value = value.replace(/(^['"]|['"]$)/g, '').trim() + // set booleans appropriately instead of boolean strings + if (value === 'true') { + value = true + } else if (value === 'false') { + value = false + } + obj[key] = value } }) diff --git a/test/.env b/test/.env index dde822f5..726f77f5 100644 --- a/test/.env +++ b/test/.env @@ -16,3 +16,5 @@ RETAIN_INNER_QUOTES={"foo": "bar"} RETAIN_INNER_QUOTES_AS_STRING='{"foo": "bar"}' INCLUDE_SPACE=some spaced out string USERNAME="therealnerdybeast@example.tld" +FALSEY_VALUE=false +TRUTHY_VALUE=true diff --git a/test/main.js b/test/main.js index f373ed50..9f7745d4 100644 --- a/test/main.js +++ b/test/main.js @@ -179,5 +179,11 @@ describe('dotenv', function () { parsed.should.have.property('USERNAME', 'therealnerdybeast@example.tld') done() }) + + it('parses booleans correctly', function (done) { + parsed.should.have.property('FALSEY_VALUE', false) + parsed.should.have.property('TRUTHY_VALUE', true) + done() + }) }) })