How to change the Node.js module wrapper ?
Module Wrapper Function: Under the hood, NodeJS does not run our code directly, it wraps the entire code inside a function before execution. This function is termed as Module Wrapper Function. Refer https://nodejs.org/api/modules.html#modules_the_module_wrapper for official documentation.
Before a module’s code is executed, NodeJS wraps it with a function wrapper that has the following structure:
(function (exports, require, module, __filename, __dirname) { //module code });
Use of Module Wrapper Function in NodeJS:
- The top-level variables declared with var, const, or let are scoped to the module rather than to the global object.
- It provides some global-looking variables that are specific to the module, such as:
- The module and exports object that can be used to export values from the module.
- The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path.
Modifying Module Wrapper Function: Consider that we have two files, main.js and module.js. In main.js we overwrite the Module.wrap function in order to console.log(‘modifedMWF’); every time a module is required. Now if we require module.js, it contains a message to confirm whether our modifications are successful or not.
- This is the first file which will call second.
main.js
var
Module = require(
"module"
);
(
function
(moduleWrapCopy) {
Module.wrap =
function
(script) {
script =
"console.log('modifiedMWF');"
+ script;
return
moduleWrapCopy(script);
};
})(Module.wrap);
require(
"./module.js"
);
- This is the second file.
module.js
console.log(
"Hello Beginner from module.js!"
);
Output: Running main.js, we get the following output that confirms our successful alteration in Module Wrapper Function.
node main.js