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

若如初见. 提交于 2019-12-02 22:18:06

The module that you write can export a single function. When you require the module, call the function with your initialization argument. That function can return an Object (hash) which you place into your variable in the require-ing module. In other words:

main.js

var initValue = 0;
var a = require('./arithmetic')(initValue);
// It has functions
console.log(a);
// Call them
console.log(a.addOne());
console.log(a.subtractOne());

arithmetic.js:

module.exports = function(initValue) {
  return {
    addOne: function() {
      return initValue + 1;
    },
    subtractOne: function() {
      return initValue - 1;
    },
  }
}

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();

What about workaround like export some init method and pass objectX as parameter right after requiring?

var module = require('moduleJS');
module.init(objectX)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!