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.