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

前端 未结 4 1462
生来不讨喜
生来不讨喜 2020-12-13 13:54

In my app.js I have below 3 lines.

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


        
相关标签:
4条回答
  • 2020-12-13 14:07

    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){
    
     ...
    
    }
    
    0 讨论(0)
  • 2020-12-13 14:11

    You should just put the same code in 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.....
    }
    

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

    0 讨论(0)
  • 2020-12-13 14:23

    Why do you use require, for scr, no prom use source. It's the same as require and we can pass args in this fuction.

    var x="hello i am you";
    console.log(require(x));  //error
    console.log(source(x));   //it will run without error
    
    0 讨论(0)
  • 2020-12-13 14:29

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

    Specifically answering your question:

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

    In user.js:

    exports.find = function(id){
      // you can do:
      // module.parent.client.query.....
    }
    
    0 讨论(0)
提交回复
热议问题