Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

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?

like image 470
user482594 Avatar asked Feb 05 '12 04:02

user482594


People also ask

For what require () is used in NodeJS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

What happens when we require a module in NodeJS?

If the module is native, it calls the NativeModule. require() with the filename and returns the result. Otherwise, it creates a new module for the file and saves it to the cache. Then it loads the file contents before returning its exports object.

Can you use require in a module?

The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node. js application, you can simply use the require() method.


2 Answers

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){   ...  } 
like image 55
Dslayer Avatar answered Sep 20 '22 13:09

Dslayer


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..... } 
like image 21
Shripad Krishna Avatar answered Sep 19 '22 13:09

Shripad Krishna