62

I'm trying to setup my own nodejs server, but I'm having a problem. I can't figure out how to see changes to my application without restarting it. Is there a way to edit the application and see changes live with node.js?

Robert Hurst
  • 8,902
  • 5
  • 42
  • 66
  • 1
    A better scenario is to use two servers as proxy, the secondary fall-down proxy server is handled by nginx when the first one gets offline(504error) (with nginx you can edit configuration with reloading / not restarting), this way all requests are switched to secondary server automatically after stopping first server, the second server is used as a backup in order to update the files at the first server. When first is back online nginx will switch to first server. With this solution you don't lose any requests. – Ardit Hyka Sep 19 '17 at 22:11

9 Answers9

60

Nodules is a module loader for Node that handles auto-reloading of modules without restarting the server (since that is what you were asking about):

http://github.com/kriszyp/nodules

Nodules does intelligent dependency tracking so the appropriate module factories are re-executed to preserve correct references when modules are reloaded without requiring a full restart.

Kris Zyp
  • 621
  • 4
  • 3
53

Check out Node-Supervisor. You can give it a collection of files to watch for changes, and it restarts your server if any of them change. It also restarts it if it crashes for some other reason.

"Hot-swapping" code is not enabled in NodeJS because it is so easy to accidentally end up with memory leaks or multiple copies of objects that aren't being garbage collected. Node is about making your programs accidentally fast, not accidentally leaky.

EDIT, 7 years after the fact: Disclaimer, I wrote node-supervisor, but had handed the project off to another maintainer before writing this answer.

isaacs
  • 16,656
  • 6
  • 41
  • 31
  • 2
    it should be fine to hot swap in development, after a server restart it will be OK, that's not to say it would be easy to implement – Alexander Mills Sep 13 '15 at 02:34
  • The link you've provided seems to suggest that this is your project. Could you clarify your involvement and add appropriate disclaimers (if appropriate)? – HPierce Sep 17 '16 at 18:21
  • Last commit on 2017, Dec. Any alternative or is this still a good solution? – user3290525 Jul 26 '20 at 05:49
  • @user3290525 [nodemon](https://github.com/remy/nodemon) was recommended [here](https://github.com/petruisfan/node-supervisor/issues/215). –  Sep 24 '20 at 14:03
12

if you would like to reload a module without restarting the node process, you can do this by the help of the watchFile function in fs module and cache clearing feature of require:

Lets say you loaded a module with a simple require:

var my_module = require('./my_module');

In order to watch that file and reload when updated add the following to a convenient place in your code.

fs.watchFile(require.resolve('./my_module'), function () {
    console.log("Module changed, reloading...");
    delete require.cache[require.resolve('./my_module')]
    my_module = require('./my_module');
});

If your module is required in multiple files this operation will not affect other assignments, so keeping module in a global variable and using it where it is needed from global rather than requiring several times is an option. So the code above will be like this:

global.my_module = require ('./my_module');
//..
fs.watchFile(require.resolve('./my_module'), function () {
    console.log("Module changed, reloading...");
    delete require.cache[require.resolve('./my_module')]
    global.my_module = require('./my_module');
});
Tahsin Turkoz
  • 4,356
  • 1
  • 27
  • 18
9

Use this: https://github.com/remy/nodemon

Just run your app like this: nodemon yourApp.js

Loolooii
  • 8,588
  • 14
  • 66
  • 90
7

There should be some emphasis on what's happening, instead of just shotgunning modules at the OP. Also, we don't know that the files he is editing are all JS modules or that they are all using the "require" call. Take the following scenarios with a grain of salt, they are only meant to describe what is happening so you know how to work with it.

  1. Your code has already been loaded and the server is running with it

    • SOLUTION You need to have a way to tell the server what code has changed so that it can reload it. You could have an endpoint set up to receive a signal, a command on the command line or a request through tcp/http that will tell it what file changed and the endpoint will reload it.

      //using Express
      var fs = require('fs');
      app.get('reload/:file', function (req, res) {
          fs.readfile(req.params.file, function (err, buffer) {
              //do stuff...
          });
      });
      
  2. Your code may have "require" calls in it which loads and caches modules

    • SOLUTION since these modules are cached by require, following the previous solution, you would need a line in your endpoint to delete that reference

      var moduleName = req.params.file;
      delete require.cache[moduleName];
      require('./' + moduleName);
      

There's a lot of caveats to get into behind all of this, but hopefully you have a better idea of what's happening and why.

Sparkida
  • 422
  • 4
  • 9
3

What's “Live Coding”?

In essence, it's a way to alter the program while it runs, without restarting it. The goal, however, is to end up with a program that works properly when we (re)start it. To be useful, it helps to have an editor that can be customized to send code to the server.

Take a look: http://lisperator.net/blog/livenode-live-code-your-nodejs-application/

3

You can also use the tool PM2. Which is a advanced production process tool for node js. http://pm2.keymetrics.io/

nidhin
  • 419
  • 1
  • 4
  • 16
1

I think node-inspector is your best bet.

Similar to how you can Live Edit Client side JS code in Chrome Dev tools, this utilizes the Chrome (Blink) Dev Tools Interface to provide live code editing.

https://github.com/node-inspector/node-inspector/wiki/LiveEdit

Gaurav Ramanan
  • 3,655
  • 2
  • 21
  • 29
0

A simple direct solution with reference to all answers available here:

Node documentation says that fs.watch is more efficient than fs.watchFile & it can watch an entire folder.

(I just started using this, so not really sure whether there are any drawbacks)

fs.watch("lib", (event_type, file_name) => {
    console.log("Deleting Require cache for " + file_name);
    delete require.cache[ require.resolve("./lib/" + file_name)];
});
Dumi Jay
  • 1,057
  • 10
  • 10