Env
.env file
- Environment variables in Node are used to store sensitive data such as passwords, API credentials, and other information that should not be written directly in code
HOST = 192.168.1.10
DBPORT = 3306
DBNAME = mydb
DBUSER = apiuser
DBPWD = 123456
PORT = 3001
Change Environment
console.log(process.env.NODE_ENV); //default is undefined
console.log(app.get('env')); //default env is development
//we can define current environment in console
> $env:NODE_ENV='developement'
> $env:NODE_ENV='testing'
> $env:NODE_ENV='production'
Get environment variables
const dotenv = require('dotenv');
dotenv.config({path:'./.env'});
console.log(process.env.NODE_ENV); //what is our current running environment, default is undefined
console.log(app.get('env')); //default env is development
console.log(process.env.DBNAME); //what is set inside env file
console.log(process.env.DBUSER); //what is set inside env file
console.log(process.env.DBPWD); //what is set inside env file
//e.g. use it to connect to mongodb
mongoose.connect('mongodb://' + process.env.HOST + ':' + process.env.DBPORT + '/' + process.env.DBNAME)
.then(()=>console.log("connected to mongodb"))
.catch(error=>console.log("connection to mongodb failed",error))
app.listen(process.env.PORT,()=>{
console.log('api listening at port '+ process.env.PORT);
});
Log when env is in development
const exporess = require('express');
const morgan = require('morgan');
const app = express();
if(app.get('env')==='development'){
appuse(morgan('tiny'));
}
Set env to production
$ export NODE_ENV=production
$ nodemon
Different config files for each environments
//install config package
$ npm i config
//then create a directory config, inside it, create 3 files
//default.json
{
"name":"myapp - development",
"dbhost":"localhost",
"dbname":"myapp-dev"
}
//development.json
{
"name":"myapp - development",
"dbhost":"localhost",
"dbname":"myapp-dev"
}
//production.json
{
"name":"myapp - production",
"dbhost":"localhost",
"dbname":"myapp-prod"
}
//now we can use in index.js
const config = require('config');
console.log(config.get('name'));
console.log(config.get('dbhost'));
console.log(config.get('dbname'));
//when we change env to production by
//$ export NODE_ENV=production
//and restart the app, the values will correspond to our settings
store sensitive info in custom environment variables
//create a file called custom-environment-variables.json
//this file only has mapping of env variables
{
"password":"PASSWORD" //the actual PASSWORD is set in the .env file, here is a mapping of that password
}
//and in the .env file
PASSWORD=123456
//now we can use in index.js
const config = require('config');
console.log(config.get('password'));