-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
66 lines (53 loc) · 1.66 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
const DEFAULT_OPTIONS = { debug: false }
const load = async (fname = '.env', options = {}) => {
if(typeof fname === 'object') {
options = fname
fname = '.env'
}
options = Object.assign({}, DEFAULT_OPTIONS, options)
const effectiveFilename = join(process.cwd(), fname)
try {
if(options.debug) {
console.log(`env-wrapper: loading env file...`)
}
const data = await readFile(effectiveFilename, 'utf8')
data.split('\n').forEach(line => {
if (line.includes('=')) {
const [key, ...values] = line.split('=')
const privateKey = key.trim().endsWith('*')
const setKey = privateKey ? key.trim().slice(0, -1) : key.trim()
const setValue = values.join('=').trim()
process.env[setKey] = setValue
if(options.debug) {
console.log(`env-wrapper: added env variable "${setKey}" as "${privateKey ? '(private)' : setValue}"`)
}
}
})
}
catch (err) {
if(err.code === 'ENOENT') {
if(options.debug) {
console.log(`env-wrapper: no environment file found ("${effectiveFilename}")`)
}
}
else {
throw err
}
}
}
const require = (key, defaultValue) => {
if (process.env[key] === undefined) {
if (defaultValue === undefined) {
throw new Error(`The environment variable "${key}" is not defined, and no default value is available`)
}
else {
process.env[key] = defaultValue
}
}
return process.env[key]
}
const get = (key) => process.env[key]
const set = (key, value) => process.env[key] = value
export default { load, require, get, set }