Created
November 29, 2020 05:03
-
-
Save Kevinwkd/104909cb0dae1ad61ad80405a15e509a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Populates process.env from .env file | |
function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { | |
let dotenvPath = path.resolve(process.cwd(), '.env') | |
let encoding /*: string */ = 'utf8' | |
let debug = false | |
if (options) { | |
if (options.path != null) { | |
dotenvPath = options.path | |
} | |
if (options.encoding != null) { | |
encoding = options.encoding | |
} | |
if (options.debug != null) { | |
debug = true | |
} | |
} | |
try { | |
// specifying an encoding returns a string instead of a buffer | |
const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) | |
Object.keys(parsed).forEach(function (key) { | |
if (!Object.prototype.hasOwnProperty.call(process.env, key)) { | |
process.env[key] = parsed[key] | |
} else if (debug) { | |
log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) | |
} | |
}) | |
return { parsed } | |
} catch (e) { | |
return { error: e } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment