I'm studying a NodeJs course, the main purpose of this course is to learn NodeJS without using npm, so we reached a stage where we defined our environment variable for staging and production, and I couldn't switch between the NODE_ENV from cmd terminal, we have a config.js file that exports the environment, the index.js imports them and based on the NODE_ENV asked for, it give it to you . -so this is the config.js script :
/*
**** Creating and exporting config variables
*/
//
var environments = {};
//
environments.staging ={
'port' : 3000,
'envName' : 'staging',
}
environments.production ={
'port' : 5000,
'envName' : 'production',
}
//
var currentEnvironment = typeof(process.env.NODE_ENV) == 'string' ? process.env.NODE_ENV.toLowerCase() :'';
//
var environmentToExport = typeof(environments[currentEnvironment]) == 'object' ? environments[currentEnvironment] : environments.staging;
//
module.exports = environmentToExport;
and the Index.js script is this :
var http = require('http');
var url = require('url');
var stringDecoder = require('string_decoder').StringDecoder;
var config = require('./config');
var server = http.createServer((req,res)=>{ to many lines i coudln't paste them });
server.listen(config.port,()=>{
console.log("Server listening on port Nº : "+config.port+" in "+config.envName+" environment ");
});
So how can I choose the NODE_ENV from terminal ?
As the NODE_ENV is an Environment Variable, you can change this option on the terminal session with the command set (on CMD):
set NODE_ENV=production
node index.js