Last Updated: February 25, 2016
· reaktivo

Load environment variables

When I'm working on a new Node.js project, I'like to make my app start by trying to read a local file called .env.js or outside version control.

With Coffeescript:

_ = require 'underscore'

// Try to load env vars
try _.extend process.env, require './.env' catch err

Then on my env file I can just export my env vars like this:

module.exports = 
  my_api_key: "1234"
  my_api_secret: "5678"

The require call is wrapped in a try catch so it doesn't fail on my production environment, where I've set my environment variables by any another method. It seems there is no concise way to look if a file will be found by the require method, inside the modules path.