Skip to content

Instantly share code, notes, and snippets.

@einarlove
Created March 18, 2016 14:58
Show Gist options
  • Select an option

  • Save einarlove/a08314587be5b4dded99 to your computer and use it in GitHub Desktop.

Select an option

Save einarlove/a08314587be5b4dded99 to your computer and use it in GitHub Desktop.
load local .env files with app.json as manifest
const path = require('path')
const fs = require('fs')
import attempt from 'lodash/attempt'
const app = require('./app.json')
const readDotEnv = filePath => attempt(
fs.readFileSync(filePath, 'utf-8').split('\n').filter(Boolean)
)
// Patch process.env from .env
const lines = readDotEnv(path.resolve('./.env'))
lines.forEach((line, index) => {
const matches = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
if (!matches) {
throw new Error(`Could not parse .env line #${index + 1}: ${line}`)
}
const key = matches[1]
const value = matches[2]
const missing = typeof process.env[key] === 'undefined'
if (missing) {
process.env[key] = value
}
})
// Patch process.env from app.json
Object.keys(app.env).forEach(key => {
const required = app.env[key].required
const value = app.env[key].value
const missing = required && typeof process.env[key] === 'undefined'
if (missing) {
if (value) {
process.env[key] = value
} else {
console.warn(`Warning: process.env.${key} is missing.`) // eslint-disable-line
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment