How to change the Node.js module wrapper?

僤鯓⒐⒋嵵緔 提交于 2019-12-03 23:18:40

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.

Aminadav Glickshtein

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.

You cannot change the wrapper inside node app, without override the require function. but you can fork (copy) node source to your computer, change one line & compile (build) it.

This why he love open-source :)

All you have to do is change one line of code if src/node.js file

here: https://github.com/nodejs/node/blob/master/src/node.js#L990

NativeModule.wrapper = [
    '(function (exports, require, module, __filename, __dirname) { ',
    '\n});'
  ];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!