Member-only story
How to Add Hooks to Node.js’ Require Function?
Node.js is a JavaScript runtime environment based on the Chrome V8 engine. The early Node.js adopted the CommonJS module specification, and the ECMAScript Modules feature has been officially supported since Node v13.2.0. It was not until v15.3.0 that the ECMAScript Modules feature was stable and compatible with the NPM ecosystem.

This article will introduce the workflow of the require
function in Node.js, how to make Node.js execute the ts file directly, and how to correctly hijack the require
function of Node.js to implement the hook function. Next, let’s first introduce the require
function.
require function
A Node.js application consists of modules, and each file is a module. For the CommonJS module specification, we import modules through the require
function. So when we use the require
function to import a module, what happens inside that function? Here we take a look at the process of require
through the call stack:

As can be seen from the above figure, when using require
function to import a module, the load
method of the Module object will be called to load the module. The implementation of this method is as follows:
// lib/internal/modules/cjs/loader.js
Module.prototype.load = function(filename) {
this.filename = filename;
this.paths = Module._nodeModulePaths(path.dirname(filename));const extension = findLongestRegisteredExtension(filename);Module._extensions[extension](this, filename);
this.loaded = true;
// omit part of the code
};
Note: The version of Node.js source code referenced in this article is v16.13.1
In the above code, the two important steps are:
- Step 1: Find the extension according to the file name;
- Step 2: Find the matching loader in the Module._extensions object through the parsed extension.