node.js - Node.js 中的 "Global"模块对象

标签 node.js express

我有一个用于连接到我的数据库并执行操作的模块。

然后在我的主脚本(app.js)中我实例化它,就像

var DBConn = require('./common/DBConn');

从该脚本来看,它工作得很好。但是我还有一些其他处理路由的脚本,我想对这些脚本执行一些数据库操作,但如果我使用 DBConn,它会返回一个错误,提示“DBConn 未定义”。

然后我可以在这些其他 js 文件中实例化另一个 DBConn,但这意味着我正在为每个文件创建一个连接,对吗?但我希望这些其他脚本使用 app.js 中的 DBConn 对象,这样我就不会不断建立到数据库的连接然后关闭它......(除非这是一个好主意,但对我来说它使得更有意义的是只有一个“全局”对象来处理所有应用程序的连接,仅此而已)。

(顺便说一句:我正在使用 Express)

最佳答案

您想在每个文件中 require() 您的模块。 Node 将缓存该模块。

通常,数据库连接的上下文被抽象到存储或存储库后面,并且您的其他模块与这些进行交互。如果人们直接需要像 mongoose 这样的模块,他们将在任何地方都需要 mongoose,但只在其主应用程序入口点 (app.js/server.js/whatever) 中调用连接代码。

https://nodejs.org/api/modules.html#modules_caching

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

关于node.js - Node.js 中的 "Global"模块对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33797732/

相关文章:

javascript - 查找文本中的日期

node.js - 如何在 Sequelize 中创建表以使用 Node JS 存储在 Postgresql 中

node.js - 用于传感器数据收集的 MongoDB 查询

node.js - pm2 下的自定义日志记录

node.js - 将用户数据作为实体组存储在 Google Cloud Datastore 中

node.js - 使用 sinon 模拟连接池和测试 url 参数?

node.js - Passport.socketio 在查找 session 时出现问题

node.js - 如何从 POST 正文获取 wav 文件并使用 Node JS/Express 上传

javascript - Backbone : How to talk to backend without the use of model. 保存()?

mysql - 如何将 NodeJs 响应转换为嵌套的 json 响应