How to reload a required module at runtime?

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.


If all you're looking to do is restart the server without restarting the process I would recommend using the http.Server.close method. According to the express docs the app.listen method returns an http.Server object, so a reload would look something like this:

app.js

const express = require("express");

app = express();

// Define the listener function separately so it can be used on restart
function listener() {
  console.log("app listening on port 3000");
}

// start the server and save a reference to it for our restart function
const server = app.listen(3000, listener);

// Export a restart function to be used by index.js
exports.restart = function() {
  server.close(function() {
    // Server is closed, start listening again
    server.listen(3000, listener) // Use the same listener function as app.listen
  });
};

index.js

const myModule = require("./app.js"); // Output: "app listening on port 3000"

// Restart the server, keep the process
myModule.restart(); // Output: "app listening on port 3000"