For testing purposes I need to change the Node.js Module
wrapper.
(function (exports, require, module, __filename, __dirname, process, global) {
debugger;
});
Played around with Module
I found
var Module = require("module")
Module.wrapper
-> ["(function (exports, require, module, __filename, __dirname, process, global) { ", "
});"]
Module.wrap
-> function(script) {
return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
}
Is it possible to hook into Module.wraper
or property to change the script wrapping?
You've done a great job by finding the Module.wrap
function. How about simply overwriting it?
Imagine that you have two files, main.js
and module.js
. In main.js
you overwrite the Module.wrap
function in order to console.log('debug');
every time a module is required. Then you require module.js
, which contains a hello world message.
main.js
:
var Module = require("module");
(function(moduleWrapCopy) {
Module.wrap = function(script) {
script = "console.log('debug');" + script
return moduleWrapCopy(script); // Call original wrapper function
};
}(Module.wrap)); // Pass original function to IIFE
require("./module.js");
module.js
:
console.log("Hello world from module.js!");
Executing node main.js
results in:
debug Hello world from module.js!
This also works with nested require()
calls, for example if you require("./module2.js")
in module.js
:
module.js
:
console.log("Hello world from module.js!");
require("./module2.js");
module2.js
:
console.log("Hello world from module2.js!");
In this case node main.js
produces:
debug Hello world from module.js! debug Hello world from module2.js!
Tested on Node.js 4.3.0 and 6.1.0.
You can override, the require
by your own method. For example
require = function(module_name) {
var js = openTheModuleIndexFile(module_name)
var wrapped = wrapTheModule(js)
eval(wrapped)
}
All you have to do is to implement the openTheModuleIndexFile
function, and wrapTheModule
which your wrapping function.
(Don't forget the module_name
can be exists is node_modules
of this directory, parent directory, or child directery, it's even can be just a JS file name)
I'm sure, you need to make same hacks, but in the end, it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With