I have a potentially odd use case for patching, or modifying Node's require()
function. I have the following, which works great for single threaded (or non worker) applications:
const Module = require('module');
const originalRequire = Module.prototype.require;
Module.prototype.require = function () {
// do stuff
return originalRequire.apply(this, arguments);
};
However, the third party code I need to "adjust" (not in my control), makes use of worker threads that also use require()
.
Is there a way I can modify the global require()
function that would also take affect when used in a worker thread?
All I need to do is modify the path for certain files that are imported this way, which is easily done via Array.prototype.replace
.
I've been scratching around on this for some time, so any help would be much appreciated!
Many thanks
While it's not the cleanest solution (but then again, neither is overwriting require
), you can overwrite require('worker_threads').Worker
:
const wt = require('worker_threads');
const _Worker = wt.Worker;
wt.Worker = function(...args) {
console.log('Creating a worker!');
return new _Worker(...args);
}
You could either use the constructor's options to add ['-r', '/some/module/path']
(won't work for ES6 modules) to execArgv
, causing the Worker thread to immediately require a module, or alternatively replace the "entry point" of the Worker thread to point at your own code/script, do your changes and then start the original entrypoint.