How to Use Different Environment Config with Node.js
2014/05/032 min read
bookmark this
Table of Contents
Introduction
Depending on the running environment, you may need to use different configuration files. In the Node.js world, the following module is one of the options.
Using node-env-file
Everything is on the following link:
https://www.npmjs.org/package/node-env-file
- First, you need to install the
node-env-filemodule.
npm install node-env-file --save
This command will update package.json and install the node-env-file module.
- Create your environment file, like
.env. The name can be anything, such as.env_devor.env_prod.
PORT=9000
NODE_ENV=development
- Add the following code to your Node.js server-side code. This will use the
node-env-filemodule to replace yourprocess.env.{your variable}.
var env = require('node-env-file');
env(__dirname + '/.env');
Tips
When you want to set the value to empty, you can set it like this:
IP=''
If your code is like the following, it will use 127.0.0.1 instead.
process.env.IP || '127.0.0.1'
Conclusion
The node-env-file module provides a simple way to manage different environment configurations in Node.js. By creating separate .env files for each environment, you can easily switch between development, testing, and production settings without modifying your application code.