Using dotenv, we can do something like this:
const dotenv = require('dotenv');
// Load the first .env file (e.g., .env.production)
const result1 = dotenv.config({ path: '.env.production' });
if (result1.error) {
throw result1.error;
}
// Load the second .env file (e.g., .env.development)
const result2 = dotenv.config({ path: '.env.development' });
if (result2.error) {
throw result2.error;
}
// Now, you can access the environment variables from both files
console.log(process.env.VARIABLE_FROM_ENV_PRODUCTION);
console.log(process.env.VARIABLE_FROM_ENV_DEVELOPMENT);
however, as you can see, it's writing to process.env on my behalf which I don't want, how can I store the results onto a separate variable?
In short, you can use dotenv like this to parse files to a specific object like so:
as in:
and this doesn't mutate process.env as a side-effect for example, this script will load two different env files at the command line and diff them: