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

Let's say I have the following code:


var myModule = require("./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?

Question author Azarus | Source



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');

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.

Answer author Aurora0001

Ask about this question here!