Azevedo Azevedo - 1 year ago 131
Node.js Question

Node.js module.exports parent/child variable reference

In node.js I have this scenario:


module.exports = {
dbHandler: {}

const DB_CONNECT = require('dbConnect.js');
const CHILD_MODULE = require('childModule.js');

module.exports.dbHandler = DB_CONNECT.connectDB(); // establishes the connection to the sqlite3 db

// ... give some time to module.exports.dbHandler to be loaded. (lab testing)

CHILD_MODULE.queryDB(); // <----- error occurs


var db = module.parent.exports.dbHandler;
//issue is here. Even after the parent have set dbHandler, this still empty {}.

module.exports.queryDB = function(){
db.all('SELECT * from mytable', (err, rows) => { // callback

is async, I give it a while (lab test) to load the database and updating
before calling

the error occurs when
is called.

TypeError: db.all is not a function

still an empty object
What is wrong in this code? How do I make the child's
to access the parent's

Answer Source

First of all, I will not fix your problem directly. I will try to explain my comment in above.

I have had a similar scenario in one of my projects. But I have used MongoDB. My db model looks like this:

var MongoClient = require('mongodb').MongoClient

var url = process.env.MONGO_URI
var collection = 'shortlinks'

var state = {
  db: null

exports.connect = function (done) {
  if (state.db) return done()

  MongoClient.connect(url, function (err, db) {
    if (err) return done(err)

    state.db = db

exports.get = function () {
  return state.db
and some other methods

And I have accessed this module from different places for the same database connection with this line:

var db = require('../models/db')

I can access the same db instance with getter method and other methods as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download