Playlist MyTV untuk smart TV berserta intisari rancangan bermula RM4.99 sebulan. Selanjutnya →

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.

1CAB4D9A-0046-4575-BA1C-364683989DB8.jpeg
nodemon, gotta restart ‘em all ⁽¹⁾ 🤪.

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:

1289DCD5-A9D9-4128-B664-BE7CD26D9B27.jpeg
Running NodeJS web app using npm command.

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.

25BB3981-A0A2-468F-B661-FAD413F2838D.jpeg
Running NodeJS web app using nodemon.

⁽¹⁾ https://www.reddit.com/r/ProgrammerHumor/comments/fz1nu0/npm_i_nodemon/

Komentar (0):

FB: https://www.facebook.com/100810608155424/posts/1022472018919710/

Tulis komen: