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?


Solution 1:

A good option is Node-supervisor:

npm install supervisor -g

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

supervisor app.js

Solution 2:

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

Solution 3:

forever module has a concept of multiple node.js servers, and can start, restart, stop and list currently running servers. It can also watch for changing files and restart node as needed.

Install it if you don't have it already:

npm install forever -g

After installing it, call the forever command: use the -w flag to watch file for changes:

forever -w ./my-script.js

In addition, you can watch directory and ignore patterns:

forever --watch --watchDirectory ./path/to/dir --watchIgnore *.log ./start/file

Solution 4:

Various NPM packages are available to make this task easy.

For Development

  • nodemon: most popular and actively maintained
  • forever: second-most popular
  • node-dev: actively maintained (as of Oct 2020)
  • supervisor: no longer maintained

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

  • pm2: npm install -g pm2
  • Strong Loop Process Manager: npm install -g strongloop

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