Nodejs Auto reload server restart| live to reload example

There are multiple ways we can refresh changes

  • --watchoption
  • nodemon
  • supervisor
  • forever

Nodejs projects run a web server with default node command execution. Every time if any changes to these files in the project, Need to stop/start (restart) the server manually to reload the changes.

Is there any way to reload changes without restarting the Node Server?

Yes, reload changes without restart node web server

How to Auto reload changes

There are multiple ways to do hot reload nodejs changes

  • node command with with --watch

with node 1.19 onwards, the node command has a —watch option to monitor changes in a project.

node --watch index.js
  • use the nodemon tool.

nodemon is a tool, that checks the project and monitors changes in source code, automatically restarting the server.

It monitors single or multiple files or directories.

You can install globally(-g) to work in the command line in any path.

npm install -g nodemon

or you can also add as devDependencies using the below command, It limits to a given application only.

npm install --save-dev nodemon

Once installed dependency. You can run either as command line as given below

nodemon index.js

or using npm scripts of the package.json file

{
  "scripts": {
    "run": "nodemon index.js"
  }
}
  • use supervisor

Another way to use the supervisor npm module with a hot reload feature

npm install -g supervisor
supervisor index.js

Can also use in npm scripts

{
  "scripts": {
    "run": "supervisor index.js"
  }
}
  • use forever

forever is a CLI tool to run node programs continuously forever.

npm install -g forever
forever start index.js
forever -w start index.js

option -w for watching changes files in the Node application directory or folder