Skip to content

Instantly share code, notes, and snippets.

@huntie
Last active March 25, 2019 10:45
Show Gist options
  • Save huntie/00518a9c77907873e02396762090ca40 to your computer and use it in GitHub Desktop.
Save huntie/00518a9c77907873e02396762090ca40 to your computer and use it in GitHub Desktop.
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