How to require a file in node.js and pass an argument in the request method, but not to the module?

前端 未结 3 1443
梦谈多话
梦谈多话 2021-02-03 23:47

I have a module.js that must be loaded; In order to work needs objectX;

How do I pass the objectX to the module.js in the require method provided by node.js?

tha

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 00:29

    You can avoid changing the actual exported object by chaining in an "init" method (name it whatever you want).

    Module TestModule.js:

    var x = 0; // Some private module data
    
    exports.init = function(nx) {
        x = nx; // Initialize the data
        return exports;
    };
    
    exports.sayHi = function() {
        console.log("HELLO THERE "+x);
    };
    

    And then requiring it like this:

    var TM = require('./TestModule.js').init(20);
    TM.sayHi();
    

提交回复
热议问题