2

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 ?

3
  • 1
    I think you shouldn't export your variable in a module. Instead of this, export your functions. If you really need to export your variable, write a getter function and export the getter function. Commented Oct 29, 2016 at 14:22
  • Could you post your comment as an answer and give an example, please? Commented Oct 29, 2016 at 14:23
  • Do you meant I should pass the db handler as a parameter ? Like module.exports.queryDB = function(dbHandler) Commented Oct 29, 2016 at 14:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.