Node.js – How to 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?

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