Created
June 9, 2020 19:42
-
-
Save etc-tiago/40c745adc110d7fb29e28b5e7424b54c to your computer and use it in GitHub Desktop.
Zero-dependency module that loads environment variables from a .env.json file into process.env.
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
import { readFileSync } from 'fs'; | |
import path from 'path'; | |
type Config = { | |
envPath: string; | |
encoding: BufferEncoding; | |
debug: boolean; | |
}; | |
export default ({ envPath = path.resolve(process.cwd(), '.env.json'), encoding = 'utf8', debug = false }: Config) => { | |
// load json | |
let envVars: any = {}; | |
try { | |
const loadFile = readFileSync(envPath, { encoding }); | |
envVars = JSON.parse(loadFile); | |
} catch (error) { | |
throw error; | |
} | |
Object.keys(envVars).forEach((env) => { | |
if (!Object.prototype.hasOwnProperty.call(process.env, env)) { | |
process.env[env] = envVars[env]; | |
} else if (debug) { | |
// tslint:disable-next-line: no-console | |
console.log(`"${env}" is already defined in \`process.env\` and will not be overwritten`); | |
} | |
}); | |
return { envVars }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment