[node.js] Restart node upon changing a file

For someone who is coming from PHP background the process of killing node and starting it again after every code change, seems very tedious. Is there any flag when starting a script with node to automatically restart node when code change is saved?

This question is related to node.js

The answer is


node-dev

node-dev is great alternative to both nodemon and supervisor for developers who like to get growl (or libnotify) notifications on their desktop whenever the server restarts or when there is an error or change occur in file.

Installation:

npm install -g node-dev

Use node-dev, instead of node:

node-dev app.js

Notification on Changing file so server start automatically

enter image description here

console out put

enter image description here


You can also try nodemon

To Install Nodemon

npm install -g nodemon

To use Nodemon

Normally we start node program like:

node server.js

But here you have to do like:

nodemon server.js

Various NPM packages are available to make this task easy.

For Development

For Production (with extended functionality such as clustering, remote deploy etc.)

Comparison between Forever, pm2 and StrongLoop can be found on StrongLoop's website.


I use runjs like:

runjs example.js

The package is called just run

npm install -g run

You should look at something like nodemon.

Nodemon will watch the files in the directory in which nodemon was started, and if they change, it will automatically restart your node application.

Example:

nodemon ./server.js localhost 8080

or simply

nodemon server

A good option is Node-supervisor and Node.js Restart on File Change is good article on how to use it, typically:

 npm install supervisor -g

and after migrating to the root of your application use the following

 supervisor app.js

Follow the steps:

  1. npm install --save-dev nodemon

  2. Add the following two lines to "script" section of package.json:

"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"

as shown below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
}
  1. npm run devstart

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website