-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathloadEnv.js
34 lines (29 loc) · 925 Bytes
/
loadEnv.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
const fs = require('fs')
module.exports = function loadEnv (path = '.env') {
const config = parse(fs.readFileSync(path, 'utf-8'))
Object.keys(config).forEach(key => {
process.env[key] = config[key]
})
return config
}
function parse (src) {
const res = {}
src.split('\n').forEach(line => {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1]
let value = keyValueArr[2] || ''
// expand newlines in quoted values
const len = value ? value.length : 0
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n')
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim()
res[key] = value
}
})
return res
}