Tuesday 19 February 2019

Node.js: NODE_ENV: Working with different environments


Any non-trivial application runs at least in three different environments.
a.   Development
b.   Testing
c.    Production

Depend on the type of environment, we apply specific configurations to the application. For example, enabling debug logging level in testing and development and enabling only error logging level in production etc.,

How to set the environment in node.js?
You can set the environment of the application in node.js by setting the environment variable ‘NODE_ENV’. If this environment variable is not set, then node.js runs the application on development mode.

index.js
//Load express module
const express = require('express')

//Put new Express application inside app variable
const app = express()

mode = app.get('env')
console.log(`Application running in ${mode}`)

const port = 8080

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js, you can see below messages in console.

Application running in development
Application started listening on port 8080!

As you see the console messages, node.js running in development environment.

How can you set the environment while launching the application?
You can set the ‘NODE_ENV’ variable in command line like below.

linux & mac:
export NODE_ENV=production

windows:
set NODE_ENV=production

For example, I set the environment to ‘production’ and relaunch the application.

I observed below messages in console.
Application running in production
Application started listening on port 8080!

Why to set the environment to production in nodes.js?
a.   If the application is running in development mode, no views are cached and javascript, css, etc. aren’t minimized and cached. It impacts the performance a lot. In case of development environment, this is fine. But while in production, we need to maximum performance out of the application. So always set the environment to production while launching the application in production environment.

b.   devDependencies are ignored in production environment.

I would recommend you go through below article.



Previous                                                 Next                                                 Home

No comments:

Post a Comment