Home

Awesome

require-in-the-middle

Hook into the Node.js require function. This allows you to modify modules on-the-fly as they are being required.

npm Test status

Also supports hooking into calls to process.getBuiltinModule(), which was introduced in Node.js v22.3.0.

Installation

npm install require-in-the-middle --save

Usage

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
})

API

The require-in-the-middle module exposes a single function:

hook = new Hook([modules][, options], onrequire)

When called a hook object is returned.

Arguments:

The onrequire callback will be called the first time a module is required. The function is called with three arguments:

Return the value you want the module to expose (normally the exports argument).

hook.unhook()

Removes the onrequire callback so that it will not be triggerd by subsequent calls to require() or process.getBuiltinModule().

License

MIT