How to auto-reload files in Node.js?

How to auto-reload files in Node.js?

Any ideas on how I could implement an auto-reload of files in Node.js? I’m tired of restarting the server every time I change a file.
Apparently Node.js’ require() function does not reload files if they already have been required, so I need to do something like this:
var sys = require(‘sys’),
http = require(‘http’),
posix = require(‘posix’),
json = require(‘./json’);

var script_name = ‘/some/path/to/app.js’; = require(‘./app’).app;

process.watchFile(script_name, function(curr, prev){{
process.compile( content, script_name );

http.createServer( 8080 );

And in the app.js file I have:
var file = require(‘./file’); = function(req, res) {
file.serveFile( req, res, ‘file.js’);

But this also isn’t working – I get an error in the process.compile() statement saying that ‘require’ is not defined. process.compile is evaling the app.js, but has no clue about the node.js globals.


Solution 1:

A good, up to date alternative to supervisor is nodemon:

Monitor for any changes in your node.js application and automatically restart the server – perfect for development

To use nodemon:

$ npm install nodemon -g
$ nodemon app.js

Solution 2:

node-supervisor is awesome

usage to restart on save:

npm install supervisor -g
supervisor app.js

by isaacs –

Solution 3:

i found a simple way:

delete require.cache['/home/shimin/test2.js']

Solution 4:

nodemon came up first in a google search, and it seems to do the trick:

npm install nodemon -g
cd whatever_dir_holds_my_app
nodemon app.js

Solution 5:

If somebody still comes to this question and wants to solve it using only the standard modules I made a simple example:

var process = require('process');
var cp = require('child_process');
var fs = require('fs');

var server = cp.fork('server.js');
console.log('Server started');

fs.watchFile('server.js', function (event, filename) {
    console.log('Server stopped');
    server = cp.fork('server.js');
    console.log('Server started');

process.on('SIGINT', function () {

This example is only for one file (server.js), but can be adapted to multiple files using an array of files, a for loop to get all file names, or by watching a directory:'./', function (event, filename) { // sub directory changes are not seen
    console.log(`restart server`);
    server = cp.fork('server.js');    

This code was made for Node.js 0.8 API, it is not adapted for some specific needs but will work in some simple apps.

This functional is implemented in my module simpleR, GitHub repo

Solution 6:

There is Node-Supervisor that you can install by

npm install supervisor