If you’re a web developer, you’ve probably heard of Node.js. It’s a JavaScript runtime that allows you to build scalable network applications. Node.js is popular because it’s lightweight and efficient.
Developers use Node.js for its asynchronous event-driven architecture, which makes it perfect for real-time applications like chatbots and live chat. When you’re developing a Node.js application, you’re usually working in a development environment. This is where you write and test your code.
Once you’re happy with your code, you can then deploy it to a production environment. The main difference between development and production is that production environments are usually more stable and have more resources.
This means that your Node.js application will perform better in production. It’s important to test your code in a development environment before deploying to production. This will help you catch any errors and ensure that your code is running smoothly. Lets have a look how do we do configurations for these two scenarios step by step.
Also Read
Specify Nodejs to Run In Production Mode
Nodejs always runs in development mode by default , while you are running any code , but you can switch to Production mode by setting one variable .
export NODE_ENV=production
Setting Production Mode in Nodejs In Linux or Unix
If you are using linux or unix as your server in production , you can setup .bashrc
or .bash_profile
.
$ sudo vi .bashrc
//Or
$ sudo vi .bash_profile
If you are running on Mac M1 or M2 , you can try below command
$ sudo vi ~/.zshrc
Update the below line and save the file .
export NODE_ENV=production
Why Production Mode Is Important .
Setting Production mode is necessary explicitly as most of times few of libraries we might be using has made logging enabled by default in dev mode .
Most of templating library compiles the template file when a request is sent , whereas if same mode is set as production it wont recompile every time , instead the templating files would be cached and served.
How Can we Write Conditional Code for Different modes
We might often need to enable few logs or add some logic based on Production and development mode in our code . Have a look how can we do that .
if (process.env.NODE_ENV === 'development') {
}
if (process.env.NODE_ENV === 'production') {
}
Conclusion
We have understood very important aspect of Node . This might not be helpful in development , but it proves to be handy in production to avoid any minor mishaps .