| 67 | * |
| 68 | */ |
| 69 | export function config(options?: Partial<DotenvConfigOptions>): DotenvConfigOutput { |
| 70 | const dotenvPath = options?.path || path.resolve(process.cwd(), '.env') |
| 71 | const encoding = options?.encoding || 'utf8' |
| 72 | const debug = options?.debug || false |
| 73 | |
| 74 | try { |
| 75 | // specifying an encoding returns a string instead of a buffer |
| 76 | const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) |
| 77 | |
| 78 | for (const key of Object.keys(parsed)) { |
| 79 | if (!Object.prototype.hasOwnProperty.call(process.env, key)) { |
| 80 | process.env[key] = parsed[key] |
| 81 | } else if (debug) { |
| 82 | log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | return { parsed } |
| 87 | } catch (error) { |
| 88 | return { error } |
| 89 | } |
| 90 | } |