40

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
  • 16,878
  • 21
  • 72
  • 108

4 Answers4

71

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
  • 31,675
  • 9
  • 80
  • 92
Dslayer
  • 1,101
  • 14
  • 17
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,463
  • 4
  • 52
  • 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,715
  • 9
  • 53
  • 56
-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,752
  • 35
  • 31
  • 35