Skip to content

Commit 03fb7b9

Browse files
authored
Merge pull request #31 from Platane/master
Gracefully fallback when the .env file is not found
2 parents 46e555f + 9811cd1 commit 03fb7b9

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

src/index.js

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,28 @@ var pathResolve = require('path').resolve;
55

66
var dotenvContent;
77

8+
function loadDotenvContent (opts){
9+
var dotenvPath = pathResolve(process.cwd(), '.env')
10+
var encoding = 'utf8'
11+
var debug = false
12+
if (opts.path != null) {
13+
dotenvPath = opts.path
14+
}
15+
if (opts.encoding != null) {
16+
encoding = opts.encoding
17+
}
18+
if (opts.debug != null) {
19+
debug = true
20+
}
21+
var fileContent;
22+
try { fileContent = fs.readFileSync(dotenvPath, {encoding:encoding}) } catch(e) {};
23+
dotenvContent = fileContent ? require('dotenv').parse(fileContent, {debug:debug}) : {};
24+
var dotenvExpand;
25+
try { dotenvExpand = require('dotenv-expand'); } catch(e) {}
26+
if (dotenvExpand)
27+
dotenvContent = dotenvExpand({parsed:dotenvContent, ignoreProcessEnv:true}).parsed;
28+
}
29+
830
function getValue(dotenvContent, systemContent, opts, name) {
931
if (opts.env && name in opts.env) return opts.env[name];
1032

@@ -34,23 +56,7 @@ module.exports = function (options) {
3456
if(t.isAssignmentExpression(path.parent) && path.parent.left == path.node) return;
3557
if (path.get("object").matchesPattern("process.env")) {
3658
if (!dotenvContent) {
37-
var dotenvPath = pathResolve(process.cwd(), '.env')
38-
var encoding = 'utf8'
39-
var debug = false
40-
if (state.opts.path != null) {
41-
dotenvPath = state.opts.path
42-
}
43-
if (state.opts.encoding != null) {
44-
encoding = state.opts.encoding
45-
}
46-
if (state.opts.debug != null) {
47-
debug = true
48-
}
49-
dotenvContent = require('dotenv').parse(fs.readFileSync(dotenvPath, {encoding:encoding}), {debug:debug});
50-
var dotenvExpand;
51-
try { dotenvExpand = require('dotenv-expand'); } catch(e) {}
52-
if (dotenvExpand)
53-
dotenvContent = dotenvExpand({parsed:dotenvContent, ignoreProcessEnv:true}).parsed;
59+
loadDotenvContent(state.opts);
5460
}
5561
var key = path.toComputedKey();
5662
if (t.isStringLiteral(key)) {

0 commit comments

Comments
 (0)