[Node.js] Manage Configuration Values with Environment Variables

Storing configuration in files instead of the environment has many downsides, including mistakenly checking in the wrong configuration in the wrong environment, coupling configuration with code, and scaling issues in larger server architectures.

We’ll learn how to update app code to look at environment variables for configuration values instead of using configuration files, and different approaches for managing environment variables between dev/stage/prod.

1. Create an .env file and store all the env variables in the file.
// .env

MONGO_URI=mongodb://localhost:27017/foo
2.  Using the env variable automaticlly from dotenv 
// When need to use env variables, require dotenv.
require('dotenv').config(); 
var MongoClient = require('mongodb').MongoClient;

// Then use the variable from process.env
MongoClient.connect(process.env.MONGO_URI, function(err, db) {
  if (err) {
    console.log('Cannot connect to MongoDB!', err);
  } else {
    console.log('Connected to MongoDB!');
  }
});
原文地址:https://www.cnblogs.com/Answer1215/p/8561804.html