Module to hook into the Node.js require function
npm install require-in-the-middleHook into the Node.js require function. This allows you to modify
modules on-the-fly as they are being required.


Also supports hooking into calls to process.getBuiltinModule(), which was introduced in Node.js v22.3.0.
```
npm install require-in-the-middle --save
`js
const path = require('path')
const { Hook } = require('require-in-the-middle')
// Hook into the express and mongodb module
new Hook(['express', 'mongodb'], function (exports, name, basedir) {
const version = require(path.join(basedir, 'package.json')).version
console.log('loading %s@%s', name, version)
// expose the module version as a property on its exports object
exports._version = version
// whatever you return will be returned by require`
return exports
})
The require-in-the-middle module exposes a single function:
When called a hook object is returned.
Arguments:
- modules <string[]> An optional array of module names to limit which modulesonrequire
trigger a call of the callback. If specified, this must be thereact-dom
first argument. Both regular modules (e.g. ) andreact-dom/server
sub-modules (e.g. ) can be specified in the array.options
- <Object> An optional object containing fields that change when theonrequire
callback is called. If specified, this must be the secondoptions.internals
argument.
- <boolean> Specifies whether onrequire should be calledfalse
when module-internal files are loaded; defaults to .onrequire
- <Function> The function to call when a module is required.
The onrequire callback will be called the first time a module is
required. The function is called with three arguments:
- exports <Object> The value of the module.exports property that wouldname
normally be exposed by the required module.
- <string> The name of the module being required. If options.internalstrue
was set to , the path of module-internal files that are loadedbasedir
(relative to ) will be appended to the module name, separated bypath.sep
.basedir
- <string> The directory where the module is located, or undefined
for core modules.
Return the value you want the module to expose (normally the exports
argument).
Removes the onrequire callback so that it will not be triggerd byrequire()
subsequent calls to or process.getBuiltinModule()`.