-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathparse.js
43 lines (40 loc) · 1.28 KB
/
parse.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
module.exports = {
/**
* @description Parses env file data
* @param {string | Buffer} envStr
* @returns {{
* key: string,
* value: string,
* isEnvVar: boolean,
* }[]}
*/
parse(envStr = '') {
const keyValuePattern = /^\s*([\w.-]+)\s*=\s*("[^"]*"|'[^']*'|[^#]*)?(\s*|\s*#.*)?$/;
// Covert to string when buffer & split by new line.
return envStr.toString('utf-8').split('\n').map(line => {
const parsedLine = keyValuePattern.exec(line);
// Ignore lines that do not match. When correctly parsed - len is always 4.
if (parsedLine && parsedLine.length === 4) {
const {1: envKey = null, 2: envValue = ''} = parsedLine;
if (envKey) {
const isDoubleQuoted = envValue.startsWith('"') && envValue.endsWith('"');
const isSingleQuoted = envValue.startsWith("'") && envValue.endsWith("'");
// When single or double quoted, remove quotes
const unquotedEnvValue = isDoubleQuoted || isSingleQuoted
? envValue.slice(1, -1)
: envValue;
return {
key: envKey,
value: unquotedEnvValue,
isEnvVar: true,
};
}
}
return {
key: null,
value: line.trim(),
isEnvVar: false,
};
});
}
}