如何在 node.js 中需要一个文件并在请求方法中传递一个参数,而不是传递给模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8834168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:00:29  来源:igfitidea点击:

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

node.jsrequire

提问by Totty.js

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

我有一个必须加载的 module.js;为了工作需要objectX;

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

node.js提供的require方法中如何将objectX传递给module.js?

thanks

谢谢

// my module.js
objectX.add('abc');
// error: objectX is undefined

I would like a way to do it, without having to change all my classes because would take a lot of time... and they way it is has good performance for the client side. (I mix clientfiles with serverfiles***)

我想要一种方法来做到这一点,而不必更改我的所有课程,因为会花费很多时间......而且他们的方式对客户端具有良好的性能。(我将客户端文件与服务器文件混合使用***)

回答by kgilpin

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:

您编写的模块可以导出单个函数。当您需要该模块时,请使用您的初始化参数调用该函数。该函数可以返回一个对象(哈希),您将其放入 require-ing 模块中的变量中。换句话说:

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:

算术.js:

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

回答by ChrisCantrell

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

您可以通过链接“init”方法(随意命名)来避免更改实际导出的对象。

Module TestModule.js:

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

回答by ladar

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

像导出一些 init 方法并在需要后立即将 objectX 作为参数传递之类的解决方法怎么样?

var module = require('moduleJS');
module.init(objectX)