如何在node.js中要求一个文件并在request方法中传递一个参数,而不是传递给模块? [英] How to require a file in node.js and pass an argument in the request method, but not to the module?
问题描述
我有一个必须加载的module.js;为了工作需要objectX;
I have a module.js that must be loaded; In order to work needs objectX;
如何通过node.js提供的require方法将objectX传递给module.js?
How do I pass the objectX to the module.js in the require method provided by node.js?
谢谢
// 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***)
推荐答案
您编写的模块可以导出单个函数.当您需要该模块时,请使用您的初始化参数调用该函数.该函数可以返回一个对象(哈希),您将其放入需求模块中的变量中.换句话说:
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:
arithmetic.js:
module.exports = function(initValue) {
return {
addOne: function() {
return initValue + 1;
},
subtractOne: function() {
return initValue - 1;
},
}
}
这篇关于如何在node.js中要求一个文件并在request方法中传递一个参数,而不是传递给模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!