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?
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.
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.
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.
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){ ... }
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..... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With