Skip to content

Instantly share code, notes, and snippets.

@Kevinwkd
Created November 29, 2020 05:03
Show Gist options
  • Save Kevinwkd/104909cb0dae1ad61ad80405a15e509a to your computer and use it in GitHub Desktop.
Save Kevinwkd/104909cb0dae1ad61ad80405a15e509a to your computer and use it in GitHub Desktop.
// 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