Skip to content

Instantly share code, notes, and snippets.

@etc-tiago
Created June 9, 2020 19:42
Show Gist options
  • Save etc-tiago/40c745adc110d7fb29e28b5e7424b54c to your computer and use it in GitHub Desktop.
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.
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