在node.js中使用`require`时如何传递变量? [英] How can I pass a variable while using `require` in node.js?

查看:1347
本文介绍了在node.js中使用`require`时如何传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my app.js I have below 3 lines.

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

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

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

user.js

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

显然,我想在user.js文件中使用client.无论如何,当我使用require方法时,可以将此client传递给user.js文件吗?

Apparently, I want to use client inside of the user.js file. Is there anyway that I can pass this client to the user.js file, while I am using require method?

推荐答案

我认为您想做的是:

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){

 ...

}

这篇关于在node.js中使用`require`时如何传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆