|
1 | | -function getEachLines(content: string): string[] { |
2 | | - return content.split('\n').filter((line) => line.trim() !== '') // remove empty lines |
3 | | -} |
4 | | - |
5 | | -function removeComments(content: string[]): string[] { |
6 | | - return content.filter((line) => !line.startsWith('#')) |
7 | | -} |
8 | | - |
9 | | -function getKeyValue(content: string): { key: string; value: string } { |
10 | | - const [key, value] = content.split(/=(.+)/) // split on the first = and the rest of the line |
11 | | - if (!key || !value) { |
12 | | - throw new Error('Invalid .env') |
13 | | - } |
14 | | - return { |
15 | | - key: key.replace(/[\n\r'"]+/g, ''), |
16 | | - value: value.replace(/[\n\r'"]+/g, ''), |
17 | | - } |
18 | | -} |
| 1 | +import { parse } from 'dotenv' |
19 | 2 |
|
20 | 3 | export function parseEnvFile(content: string, withIndex: boolean = false): |
21 | 4 | { index?: number; key: string; value: string }[] { |
22 | | - const lines = getEachLines(content) |
23 | | - const filteredLines = removeComments(lines) |
24 | | - return filteredLines.map((line, index) => { |
25 | | - const { key, value } = getKeyValue(line) |
26 | | - if (withIndex) { |
27 | | - return { index, key, value } |
28 | | - } |
29 | | - return { key, value } |
30 | | - }) |
| 5 | + try { |
| 6 | + const parsed = parse(content) |
| 7 | + |
| 8 | + const variables = Object.entries(parsed).map(([key, value], index) => { |
| 9 | + const result: { index?: number; key: string; value: string } = { |
| 10 | + key, |
| 11 | + value: value || '' |
| 12 | + } |
| 13 | + |
| 14 | + if (withIndex) { |
| 15 | + result.index = index |
| 16 | + } |
| 17 | + |
| 18 | + return result |
| 19 | + }) |
| 20 | + |
| 21 | + return variables |
| 22 | + } catch (error) { |
| 23 | + throw new Error('Invalid .env file format') |
| 24 | + } |
31 | 25 | } |
0 commit comments