5

Is there a way change a node.js while it's running?

Like edit the javascript files while it's running and then it change accordingly while it's running.

GlassGhost
  • 16,906
  • 5
  • 32
  • 45

5 Answers5

6

Yes.

You'll have to load your file through another file that watches the script for changes. You will probably need some setup/teardown code that runs in the script whenever it is restarted.

var fs = require('fs');
var file = 'file.js';

var script;
function loadScript() {
  if (script) {
    if (typeof script.teardown === 'function') {
      script.teardown();
    }
    delete require.cache[file];
  }

  script = require(file);
}

fs.watch(file, function(event, filename) {
  if (event !== 'change') return;
  loadScript();
});

loadScript();

The fs.watch API is not 100% consistent across platforms, and is unavailable in some situations.

fent
  • 17,861
  • 15
  • 87
  • 91
2

Have you checked Node-supervisor

almypal
  • 6,612
  • 4
  • 25
  • 25
1

You can use nodemon.

nodemon will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application.

Perfect solution to work with Node during development.

Sam G
  • 1,242
  • 15
  • 12
  • great for development. But if I understand correctly, it does restart your server, so it is not something you can use to fix a running production server without reboot. – bvdb Nov 08 '19 at 15:14
1

No, it is not possible. When you startup a Node server / app it will load in the current versions of the files. If you make a change after startup it will be unaware. You will have to kill the app and restart for these changes to take affect.

There are some utilities like node-dev which do this for you. They monitor the filesystem for changes and restart the app as needed (along with some other features like growl notification).

I prefer restarting the app manually. That way you know exactly what version it's running, and can save changes to a file multiple times before deciding to try it out again.

Marshall
  • 4,716
  • 1
  • 19
  • 14
0

This is totally possible.

Just don't require your modules in the header; instead, load them by calling at the time of need.

In addition, you can also call require.undef('./myModule') to ditch existing versions before including the new module. You can scan the file system for any new module names, if you feel like dropping in new behavior at runtime.

I have implemented the plugin pattern numerous times with node, such that a submodule update will include new plugins that will be picked up at runtime.

Enjoy.

deepelement
  • 2,457
  • 1
  • 25
  • 25