Open In App

How to change the Node.js module wrapper ?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  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 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.

  1. 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");

    
    

  2. This is the second file.

    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


Last Updated : 07 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads