Auto restart NodeJS web app when made changes to source code using nodemon
Isnin, 4 Disember 2023, 11:45 am0
During development of NodeJS web app, we need to stop the current process of the app & re-run it again to see the changes we made to the source code.
This is because NodeJS web app itself is a web server, in contrast to web app development using PHP, where web server is a separate program from the PHP web app.
Here’s how they work:
In PHP web app, web server such as Apache, Nginx or Litespeed have been configured to handle HTTP request to .php
file, by running the target PHP file and returning the output as HTTP response.
This separation enables the PHP file to be modified without the need to restart the server. When there’s a new request to the same PHP file, web server will run the updated PHP file.
While in NodeJS, when we run the .js
file, it starts a web server that have been programmed to handle HTTP request with specific response. If we modified the source code, the web server is still running the previous code & still handle the same request & return the same response. That’s why it need to be restarted to run the updated code.
nodemon is the module that we’re going to use to watch our NodeJS web app .js
files & auto restart the NodeJS process when it detect any changes to the source code.
Here’s the demo:
mkdir nodemon npm init -y npm install express -y npm install nodemon —save-dev -y
Create app.js
file with this code:
var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('Helo wolf'); }); app.listen(8080);
Edit package.json
file, we want to use npm
to run this app. Add this line under scripts
key:
{ ... "scripts": { ... "app": "node app.js", } }
Run the app:
npm run app
Check http://localhost:8080
in browser, you should see output like this:
For now it runs without nodemon, so any changes to app.js
won’t be reflected even when you refresh the browser.
To run app.js
with nodemon, edit package.json
and add this line under scripts
key:
"dev": "./node_modules/.bin/nodemon app.js"
Run the app:
npm run dev
Edit app.js by adding <h1>
tag to the output:
res.send('<h1>Helo wolf</h1>');
After the JS file have been saved, you should see the app has been restarted in Terminal. Refresh the browser, you’ll see the changes have been applied.
⁽¹⁾ https://www.reddit.com/r/ProgrammerHumor/comments/fz1nu0/npm_i_nodemon/