Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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?

Problem courtesy of: user482594

Solution

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

 ...

}
Solution courtesy of: Dslayer

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×