Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'; this.app = require('./app').app;  process.watchFile(script_name, function(curr, prev){     posix.cat(script_name).addCallback(function(content){         process.compile( content, script_name );     }); });  http.createServer(this.app).listen( 8080 ); 

And in the app.js file I have:

var file = require('./file'); this.app = 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.

like image 215
disc0dancer Avatar asked Dec 29 '09 00:12

disc0dancer


People also ask

How do I reload node server?

Live Reload Frontend along with node server: To do this we are going to use livereload package. Fire up the terminal and run npm install livereload. Now inside your main server file In my case I have server. js Inside this file, we have to require livereload package and then reload(your_server_var); function.

Can Nodemon refresh browser?

When Nodemon restarts the ExpressJS server on changes, Livereload recreates the server and sends to the browser a refresh command when connected liveReloadServer. refresh("/"); . app.


2 Answers

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 with version of Node without npx (v8.1 and below, not advised):

$ npm install nodemon -g $ nodemon app.js 

Or to use nodemon with versions of Node with npx bundled in (v8.2+):

$ npm install nodemon $ npx nodemon app.js 

Or as devDependency in with an npm script in package.json:

"scripts": {   "start": "nodemon app.js" }, "devDependencies": {   "nodemon": "..." } 
like image 181
Marius Butuc Avatar answered Sep 18 '22 06:09

Marius Butuc


node-supervisor is awesome

usage to restart on save for old Node versions (not advised):

npm install supervisor -g supervisor app.js 

usage to restart on save for Node versions that come with npx:

npm install supervisor npx supervisor app.js 

or directly call supervisor in an npm script:

"scripts": {   "start": "supervisor app.js" } 
like image 33
Anup Bishnoi Avatar answered Sep 17 '22 06:09

Anup Bishnoi