forked from rolodato/dotenv-safe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (41 loc) · 1.39 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'use strict';
var dotenv = require('dotenv');
var fs = require('fs');
function difference (arrA, arrB) {
return arrA.filter(function (a) {
return arrB.indexOf(a) < 0;
});
}
function compact (obj) {
var result = {};
Object.keys(obj).forEach(function (key) {
if (obj[key]) {
result[key] = obj[key];
}
});
return result;
}
module.exports = {
config: function (options) {
options = options || {};
options.silent = options.silent || !fs.existsSync('.env');
// Original object that is parsed by dotenv.
var parsedObj = dotenv.load(options);
var sampleVars = dotenv.parse(fs.readFileSync(options.sample || '.env.example'));
var allowEmptyValues = options.allowEmptyValues || false;
var processEnv = allowEmptyValues ? process.env : compact(process.env);
var missing = difference(Object.keys(sampleVars), Object.keys(processEnv));
if (missing.length > 0) {
throw new Error('Missing environment variables: ' + missing.join(', '));
}
// return original object or assemble from process.env
return parsedObj
? parsedObj
: Object.keys(sampleVars).reduce(function (acc, key) {
acc[key] = process.env[key]
return acc;
}, {});
},
parse: dotenv.parse
};
module.exports.load = module.exports.config;