* Parse .env file content * ported from https://github.com/motdotla/dotenv/blob/master/lib/main.js#L49 * @param {string | Buffer} src the source content to parse * @returns {Env} parsed environment variables object
(src)
| 38 | * @returns {Env} parsed environment variables object |
| 39 | */ |
| 40 | function parse(src) { |
| 41 | const obj = /** @type {Env} */ (Object.create(null)); |
| 42 | |
| 43 | class="cm">// Convert buffer to string |
| 44 | let lines = src.toString(); |
| 45 | |
| 46 | class="cm">// Convert line breaks to same format |
| 47 | lines = lines.replace(/\r\n?/g, class="st">"\n"); |
| 48 | |
| 49 | /** @type {null | RegExpExecArray} */ |
| 50 | let match; |
| 51 | |
| 52 | while ((match = LINE.exec(lines)) !== null) { |
| 53 | const key = match[1]; |
| 54 | |
| 55 | class="cm">// Default undefined or null to empty string |
| 56 | let value = match[2] || class="st">""; |
| 57 | |
| 58 | class="cm">// Remove whitespace |
| 59 | value = value.trim(); |
| 60 | |
| 61 | class="cm">// Check if double quoted |
| 62 | const maybeQuote = value[0]; |
| 63 | |
| 64 | class="cm">// Remove surrounding quotes |
| 65 | value = value.replace(/^(['class="st">"`])([\s\S]*)\1$/gm, "$2"); |
| 66 | |
| 67 | class="cm">// Expand newlines if double quoted |
| 68 | if (maybeQuote === class="st">'"') { |
| 69 | value = value.replace(/\\n/g, class="st">"\n"); |
| 70 | value = value.replace(/\\r/g, class="st">"\r"); |
| 71 | } |
| 72 | |
| 73 | class="cm">// Add to object |
| 74 | obj[key] = value; |
| 75 | } |
| 76 | |
| 77 | return obj; |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Resolve escape sequences |