Skip to content

Commit

Permalink
feat(dotenv): support --dotenv option
Browse files Browse the repository at this point in the history
if given, it will load values from a .env file in your project, if one exists.

BREAKING CHANGE: defaultenv will now error out if one of the files in the arguments doesn't exist.
  • Loading branch information
jedwards1211 committed Jul 6, 2017
1 parent 32db4f0 commit fea3221
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FOO=gloob
10 changes: 10 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ function defaultEnv(envFiles, options) {
options = options || {}
var setvars = {}
var key
if (options.dotenv) {
var parsed = dotenv.config().parsed
for (key in parsed) setvars[key] = parsed[key]
}
for (var i = 0; i < envFiles.length; i++) {
var file = envFiles[i]
var defaultValues
Expand All @@ -18,6 +22,11 @@ function defaultEnv(envFiles, options) {
if (!(defaultValues instanceof Object)) {
throw new Error(file + ' is invalid; it should export an object, got ' + defaultValues + ' instead')
}
for (key in defaultValues) {
if (typeof defaultValues[key] !== 'string') {
throw new Error(file + ' is invalid; value for ' + key + ' should be a string, got ' + defaultValues[key] + ' instead')
}
}
} else {
defaultValues = dotenv.parse(fs.readFileSync(file, 'utf8'))
}
Expand Down Expand Up @@ -84,6 +93,7 @@ if (!module.parent) {
}

var options = {
dotenv: myArgs.indexOf('--dotenv') >= 0,
force: myArgs.indexOf('-f') >= 0 || myArgs.indexOf('--force') >= 0,
print: myArgs.indexOf('-p') >= 0 || myArgs.indexOf('--print') >= 0,
}
Expand Down
3 changes: 3 additions & 0 deletions lib/usage.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ OPTIONS
-f, --force overwrite existing values for environment variables
(by default, existing values will be preserved)

--dotenv also loads variables from a .env file in the root directory
of your project

11 changes: 11 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,5 +176,16 @@ describe('defaultenv', function () {
done()
})
})
it("loads .env when --dotenv option is given", function (done) {
var command = process.argv[0] + ' ' +
'lib/index.js --dotenv test/foo.env ' +
process.argv[0] + " -p 'process.env.FOO'"
exec(command, {
cwd: root,
}, function (error, stdout) {
expect(stdout.trim()).to.equal('gloob')
done()
})
})
})

0 comments on commit fea3221

Please sign in to comment.