Azevedo Azevedo - 1 month ago 9
Node.js Question

Node.js module.exports parent/child variable reference

In node.js I have this scenario:

main.js

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


childModule.js

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
console.log(rows);
}


Since
DB_CONNECT.connectDB()
is async, I give it a while (lab test) to load the database and updating
module.exports.dbHandler
before calling
CHILD_MODULE.queryDB()

the error occurs when
db.all
is called.

TypeError: db.all is not a function


db
still an empty object
{}
.
What is wrong in this code? How do I make the child's
db
to access the parent's
module.exports.dbHandler
?

Answer

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
    done()
  })
}

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.

Comments