39

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 file looks just like ordinary helper methods. But, it needs interact with database.

user.js

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

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?

user482594
  • 15,910
  • 19
  • 69
  • 97

4 Answers4

69

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

 ...

}
Simon
  • 29,389
  • 8
  • 76
  • 90
Dslayer
  • 1,075
  • 13
  • 14
7

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.....
}
Community
  • 1
  • 1
Shripad Krishna
  • 10,313
  • 4
  • 51
  • 65
-3

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...

Aleksandar Vucetic
  • 14,327
  • 8
  • 50
  • 54
-5

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
David Buck
  • 3,594
  • 33
  • 29
  • 34