node.js 在node.js中使用`require`时如何传递变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9146980/
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:07:40  来源:igfitidea点击:

How can I pass a variable while using `require` in node.js?

node.js

提问by user482594

In my app.jsI have below 3 lines.

在我的app.js 中,我有以下 3 行。

var database = require('./database.js');
var client = database.client
var user = require('./user.js');

user.js file looks just like ordinary helper methods. But, it needs interact with database.

user.js 文件看起来就像普通的辅助方法。但是,它需要与数据库进行交互。

user.js

用户.js

exports.find = function(id){
  //client.query.....
}

Apparently, I want to use clientinside of the user.jsfile. Is there anyway that I can pass this clientto the user.jsfile, while I am using requiremethod?

显然,我想clientuser.js文件内部使用。无论如何,我可以在使用方法时client将其传递给user.js文件require吗?

回答by Dslayer

I think what you want to do is:

我想你想做的是:

var user = require('./user')(client)

This enables you to have client as a parameter in each function in your module or as module scope variable like this:

这使您可以将客户端作为模块中每个函数的参数或作为模块范围变量,如下所示:

module.exports = function(client){

 ...

}

回答by Shripad Krishna

This question is similar to: Inheriting through Module.exports in node

这个问题类似于:Inheriting through Module.exports in node

Specifically answering your question:

具体回答你的问题:

module.client = require('./database.js').client;
var user = require('./user.js');

In user.js:

在 user.js 中:

exports.find = function(id){
  // you can do:
  // module.parent.client.query.....
}

回答by Aleksandar Vucetic

You should just put the same code in user.js

你应该把相同的代码放在 user.js 中

app.js

应用程序.js

var client = require('./database.js').client; // if you need client here at all
var user = require('./user.js');

user.js

用户.js

var client= require('./database.js').client;
exports.find = function(id){
  //client.query.....
}

I don't see any drawbacks by doing it like this...

这样做我没有看到任何缺点......