Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept all Node's require calls

I'm trying to figure out how to intercept all Node's require calls, so that I can log them.

There are a few questions about this already but the suggested methods there fail at intercepting all require calls for me, i.e. I want to deeply intercept require calls, also those made inside my required modules, and their required modules and so on.

So far I've tried the following 3 methods:

const _req = require;
global.require = function () {
  console.log ( 'require', arguments );
  return _req.apply ( this, arguments );
};
const Module = require ( 'module' );
const _load = Module._load;
Module._load = function () {
  console.log ( 'require', arguments );
  return _load.apply ( this, arguments );
};
const Module = require ( 'module' );
const _wrap = Module.wrap;
Module.wrap = function(script) {
  const prepend = `console.log ( module.id );`;
  script = prepend + script;
  return _wrap(script);
};

But none of them worked for me.

I'm under Node.js v12 running inside Electron v5.

like image 442
Fabio Spampinato Avatar asked Jul 03 '26 14:07

Fabio Spampinato


1 Answers

In order to achieve something like this (Intercept all require calls) would would most likely need to wrap the Module.prototype.require.

Module.prototype.require = wrapWithYOURInterceptor(params);

This is done in various "intercept" require libs as you can see:

  1. intercept-require: https://github.com/bttmly/intercept-require/blob/master/lib/index.js

  2. require-hook: https://bitbucket.org/ralphv/require-hook/src/master/lib/requireHook.js

You can also just use those libs instead of embarking on a new lib etc.

like image 152
Akrion Avatar answered Jul 05 '26 04:07

Akrion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!