Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload a required module at runtime?

I would like to know how to reload a Node.js module at runtime.

Let's say I have the following code:

index.js

var myModule = require("./app.js");

app.js

var express = require("express");
express.listen(3000, function() {
    console.log("app listening on port 3000");
});

I tried multiple ways to reload my module required in the index.js module. But the Express app won't restart.

I would like to keep the index.js running, because it handles recompiling Babel modules on the fly. And the app.js module with the express server needs to be completely restarted.

Is there any way to do this without starting a second process for the app.js?

like image 328
Playdome.io Avatar asked Dec 03 '16 10:12

Playdome.io


Video Answer


2 Answers

require-uncached is an npm module that will clear the cache and load a module from source fresh each time, which is exactly what you seem to be interested in according to your title. To use this, you can simply use the following code:

const requireUncached = require('require-uncached');
requireUncached('./app.js');

Before doing this, it's probably necessary to ensure that all of the previous app.js's code (including the Express server) is stopped so that they don't conflict for the same port.

Also, I would suggest considering whether this approach is really the best answer - I'm sure a library such as pm2 could handle stopping and restarting a Node instance without the risk of unwanted data hanging around, which might cause a memory leak.

like image 114
Aurora0001 Avatar answered Oct 22 '22 09:10

Aurora0001


It's simple now, I prefer write it myself for less dependencies .


function clearModule(moduleName) {
  let mp = require.resolve(moduleName)
  if (require.cache[mp]) {
    delete require.cache[mp]
    console.log(`[clear] module: ${mp}`)
  }
}

function requireReload(moduleName) {
  clearModule(moduleName);
  return require(moduleName);
}

like image 38
NicoNing Avatar answered Oct 22 '22 10:10

NicoNing