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


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.


exports.find = function(id){

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?

2/5/2012 4:45:34 AM

Accepted Answer

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


5/21/2012 5:55:56 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow