Restart Node.js app on file changes
Don’t you wish Node.js would automatically restart your app or reload your script when one of the project files is changed / modified?
Your wish is fulfilled by a Node.js module called Node Supervisor. Node Supervisor will restart your app every time a .js file is changed in the folder it is watching. A must-have module for any development environment.
Node Supervisor should be installed as a global module so that you can use one installation for all your projects.
$ npm install supervisor -g
If that gives you a permission error, try this:
$ sudo npm install supervisor -g
Now let’s assume you are in an Express app directory. Instead of starting app.js with node, we’ll start it will supervisor:
$ supervisor app.js DEBUG: Running node-supervisor with DEBUG: program 'app.js' DEBUG: --watch '.' DEBUG: --extensions 'node|js' DEBUG: --exec 'node' DEBUG: Starting child process with 'node app.js' DEBUG: Watching directory '/home/hacksparrow/example/.' for changes. Express server listening on port 3000 in development mode
Make some changes to any .js file in the project and look at the terminal, you should see something like this:
DEBUG: crashing child DEBUG: Starting child process with 'node app.js' Express server listening on port 3000 in development mode
The debug message indicates that the app was restarted, but the event is made more obvious if you make some visible output from the route of home page. Try it.
As useful as Node Supervisor is, I recommended it to be used only in a development environment.
Alternatives to Node Supervisor are Run and Nodemon, you might want to check them out too. Run is not as feature-rich as Supervisor. Nodemon is also feature rich, but I have found it to be a CPU hog, also it doesn’t restart after some runtime exceptions.
We have used only the default options of Node Supervisor in the example above. Node Supervisor has much more to offer when it comes to monitoring file changes and restarting the app – like which directory and file types to watch etc. For more details about the module visit the node-supervisor GitHub page.