(src: string | Buffer, options?: DotenvParseOptions)
| 17 | * @returns an object with keys and values based on `src` |
| 18 | */ |
| 19 | export function parse(src: string | Buffer, options?: DotenvParseOptions): DotenvParseOutput { |
| 20 | const debug = Boolean(options && options.debug) |
| 21 | const obj = {} |
| 22 | |
| 23 | // convert Buffers before splitting into lines and processing |
| 24 | src |
| 25 | .toString() |
| 26 | .split(NEWLINES_MATCH) |
| 27 | .forEach((line: string, idx: number) => { |
| 28 | // matching "KEY' and 'VAL' in 'KEY=VAL' |
| 29 | const keyValueArr = line.match(RE_INI_KEY_VAL) |
| 30 | // matched? |
| 31 | if (keyValueArr != null) { |
| 32 | const key = keyValueArr[1] |
| 33 | // default undefined or missing values to empty string |
| 34 | let val = keyValueArr[2] || '' |
| 35 | const end = val.length - 1 |
| 36 | const isDoubleQuoted = val[0] === '"' && val[end] === '"' |
| 37 | const isSingleQuoted = val[0] === "'" && val[end] === "'" |
| 38 | |
| 39 | // if single or double quoted, remove quotes |
| 40 | if (isSingleQuoted || isDoubleQuoted) { |
| 41 | val = val.substring(1, end) |
| 42 | |
| 43 | // if double quoted, expand newlines |
| 44 | if (isDoubleQuoted) { |
| 45 | val = val.replace(RE_NEWLINES, NEWLINE) |
| 46 | } |
| 47 | } else { |
| 48 | // remove surrounding whitespace |
| 49 | val = val.trim() |
| 50 | } |
| 51 | |
| 52 | obj[key] = val |
| 53 | } else if (debug) { |
| 54 | log(`did not match key and value when parsing line ${idx + 1}: ${line}`) |
| 55 | } |
| 56 | }) |
| 57 | |
| 58 | return obj |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Loads `.env` file contents into {@link https://nodejs.org/api/process.html#process_process_env | `process.env`}. |
no test coverage detected