Node.js module.exports父/子变量参考

阿兹维多

在node.js中,我有这种情况:

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);
  }

由于DB_CONNECT.connectDB()是异步的,因此我会花一点时间(实验室测试)module.exports.dbHandler在调用CHILD_MODULE.queryDB()时发生错误之前加载数据库并进行更新db.all

TypeError: db.all is not a function

db仍然是一个空的对象{}该代码有什么问题?我如何让孩子db访问父母的孩子module.exports.dbHandler

历史者

首先,我不会直接解决您的问题。我将尝试在上面解释我的评论。

在我的一个项目中,我也遇到过类似的情况。但是我用过MongoDB。我的数据库模型如下所示:

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

而且我已经从不同的地方访问了此模块,并通过以下代码进行了相同的数据库连接:

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

我可以使用getter方法和其他方法访问相同的数据库实例。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Node.js module.exports更改主体变量

Node.js:通过module.exports在模块之间共享变量

如何在Node.js中引用module.exports内部的变量

在Node.js中声明多个module.exports

Node.js中的异步module.exports依赖项

Node.js-使用module.exports作为构造函数

Node.js中的module.exports与export

node.js中的不同module.exports模式

node.js中module.exports =函数的含义

Node.js module.exports函数从MongoDB返回数组

通过node中的module.exports获取变量

Node-Express (module.exports) 变量未定义

如何使用module.exports和require()导出Node.js中的类和超类?

IntelliJ检查说node.js不存在module.exports

Node.js Module.Exports未定义的空对象

Node.js和ES6中的module.exports与export默认

如何在Node JS中使用module.exports导出数组?

Node.js module.exports的用途是什么,如何使用它?

将参数传递给node.js中的module.exports

Node.js-WebStorm智能感知两次声明module.exports的影响

如何从AWS Lambda(Node.js)的处理程序中调用module.exports

module.exports 中的 Node.js 我的 var 不够完善

如何在 node.js 中正确使用 module.exports?

导入模块,用于node.js中module.exports的所有方法

如果没有分配给 module.exports,Node.js 'require()' 会返回什么

如何使用Azure Functions和node.js在module.exports之外发出axios请求?

Node.js-修改node_module内容

Node.Js找不到模块,module.js:471

在Node module.exports = {}中导出一个类