简体   繁体   English

Node.js中的“全局”模块对象

[英]“Global” module object in Node.js

I have a module for connecting to my DB and perform actions. 我有一个用于连接到数据库并执行操作的模块。

Then in my main script (app.js) I instantiate it like 然后在我的主脚本(app.js)中实例化它

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

And from that script it works fine. 从该脚本可以正常工作。 But then I've got some other scripts that handle routes, and I want to perform some DB stuff on those, but if I use DBConn it returns an error saying "DBConn is not defined". 但是,然后我有了其他一些处理路由的脚本,并且我想在这些脚本上执行一些DB的工作,但是如果我使用DBConn,它会返回一个错误,提示“未定义DBConn”。

Then I can just instantiate another DBConn in these other js files, but this would mean I am creating a connection for each file, right? 然后,我可以在这些其他js文件中实例化另一个DBConn,但这意味着我正在为每个文件创建连接,对吗? But I want these other scripts to use the DBConn object from the app.js, so that I'm not constantly establishing a connection to the DB and then closing it... (unless this is a good idea, but to me it makes more sense to have just one "global" object dealing with the connection over all the app and that's it). 但是我希望这些其他脚本使用来自app.js的DBConn对象,这样我就不会不断地建立与数据库的连接然后关闭它……(除非这是一个好主意,但是对我来说,它使仅使用一个“全局”对象来处理整个应用程序中的连接就更有意义了。

(BTW: I'm using Express) (顺便说一句:我正在使用Express)

You want to require() your module in each file. 您要在每个文件中都需要require()模块。 Node will cache the module. 节点将缓存模块。

Typically, the context of a DB connection is abstracted away behind stores or repositories and your other modules interact with those. 通常,数据库连接的上下文在存储或存储库之后被抽象出来,而您的其他模块则与之交互。 In cases where people are directly requiring modules like mongoose, they'll require mongoose everywhere but only call the connection code within their main application entry point (app.js/server.js/whatever). 在人们直接需要猫鼬等模块的情况下,他们将在所有地方都需要猫鼬,但仅在其主应用程序入口点(app.js / server.js / whatever)中调用连接代码。

https://nodejs.org/api/modules.html#modules_caching 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. 这意味着(除其他事项外)每次对require('foo')的调用都将返回完全相同的对象,如果它可以解析为相同的文件。

Multiple calls to require('foo') may not cause the module code to be executed multiple times. 多次调用require('foo')可能不会导致模块代码多次执行。 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. 如果要让一个模块多次执行代码,请导出一个函数,然后调用该函数。

You could use a singleton to solve this issue for you. 您可以使用单例为您解决此问题。 Please remember however that singletons come with their own set of problems (a good discussuon on singletons can be found here What is so bad about singletons? ). 但是请记住,单身带着自己的一系列问题(对单身的好discussuon可以在这里找到什么是坏对单身? )。

That said once you take into consideration the pro's and cons of singletons they can be a fantastic solution to exactly this problem. 也就是说,一旦您考虑了单例的优缺点,它们可能是解决此问题的绝妙解决方案。

Example: 例:

// database.js
var singleton = function singleton() {

    this.DbConnection = {};

    function setup(database, username, password) {
        this.DbConnection = MakeDbConnection()
    };

};

singleton.instance = null;

singleton.getInstance = function(){
    if(this.instance === null){
        this.instance = new singleton();
    }
    return this.instance;
};

module.exports = singleton.getInstance();

This can then be called elsewhere in your application like so... 然后可以在应用程序的其他位置调用它,如下所示:

// main.js
var db     = require("./database");

db.setup('db', 'root', 'pass');

db.DbConnection();

Once you have called db.setup() the first time, the db connection will be available just with the following: 第一次调用db.setup()后,数据库连接仅适用于以下内容:

// elsewhere.js
var db     = require("./database");

db.DbConnection();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM