Open In App

How to Change the Node.js Module Wrapper ?

Last Updated : 26 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Changing the Node.js module wrapper involves customizing the way modules are wrapped by modifying the Module.wrap method. This allows for altering the function wrapper used in module loading.

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.

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

  1. The top-level variables declared with var, const, or let are scoped to the module rather than to the global object.
  2. 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 tell 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.

Node
// 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");
Node
// module.js

console.log("Hello Geeks from module.js!");

Output: Running main.js, we get the following output that confirms our successful alteration in Module Wrapper Function.

node main.js
Output window

Output window on running main.js



Next Article

Similar Reads