【问题标题】:How can I pass a variable while using `require` in node.js?在 node.js 中使用`require`时如何传递变量?
【发布时间】:2012-02-27 03:40:06
【问题描述】:

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

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

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

user.js

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

显然,我想在user.js 文件中使用client。无论如何我可以将这个client 传递给user.js 文件,而我正在使用require 方法?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    我想你想做的是:

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

    这使您可以将客户端作为模块中每个函数的参数 或者像这样的模块范围变量:

    module.exports = function(client){
    
     ...
    
    }
    

    【讨论】:

      【解决方案2】:

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

      具体回答你的问题:

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

      在 user.js 中:

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

      【讨论】:

        【解决方案3】:

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

        app.js

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

        user.js

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

        我认为这样做没有任何缺点......

        【讨论】:

        【解决方案4】:

        为什么你使用require,对于scr,没有舞会使用source。和 require 一样,我们可以在这个函数中传递 args。

        var x="hello i am you";
        console.log(require(x));  //error
        console.log(source(x));   //it will run without error
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-14
          • 2015-01-16
          • 1970-01-01
          • 2012-01-18
          • 2021-05-20
          • 1970-01-01
          • 2020-12-02
          • 2014-04-20
          相关资源
          最近更新 更多