Skip to content

Instantly share code, notes, and snippets.

@huntie
Last active March 25, 2019 10:45
Embed
What would you like to do?
Load environment settings in a JavaScript project from a base .env and optional .env.<build-mode> file, using dotenv.parse (no side-effects)
const dotenv = require('dotenv');
const fs = require('fs');
const { flowRight, partial, unary } = require('lodash');
const path = require('path');
/**
* Load the environment settings for the current mode from `.env.{mode}` merged
* with any private entries defined in `.env` if present.
*
* @param {string} mode
*
* @return {Object}
*/
function getEnvironmentSettings(mode) {
const getLocalPath = unary(partial(path.resolve, __dirname));
const parseFromFile = unary(flowRight(dotenv.parse, fs.readFileSync));
return Object.assign(
{},
...[`.env.${mode}`, '.env']
.map(getLocalPath)
.filter(fs.existsSync)
.map(parseFromFile)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment