将公共变量传递到Node.js中单独的模块中的最佳方法是什么? [英] What is the best way to pass common variables into separate modules in Node.js?

查看:93
本文介绍了将公共变量传递到Node.js中单独的模块中的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将单独的路由器文件用作主应用程序和身份验证应用程序的模块。我找不到将变量(数据库客户端)传递到路由器的最佳方法。我不想对其进行硬编码或通过以下方式传递它:

I use separate router files as modules for main app and auth app. I can't get the best way to pass variables(db client) into routers. I don't want to hardcode it or pass it with:

module.exports = function(app, db) {

也许是使用单例寄存器或使用全局db变量的最佳方法?

Maybe it's best way to use singleton register or use global db variable?

您对设计模式有什么经验?哪种方法是最好的,为什么?

What is your experiense with design-patterns? Which way is the best and why?

推荐答案

我发现使用依赖注入将事物传递为最佳样式。确实看起来像您拥有的东西:

I have found using dependency injection, to pass things in, to be the best style. It would indeed look something like you have:

// App.js
module.exports = function App() {
};

// Database.js
module.exports = function Database(configuration) {
};

// Routes.js
module.exports = function Routes(app, database) {
};

// server.js: composition root
var App = require("./App");
var Database = require("./Database");
var Routes = require("./Routes");
var dbConfig = require("./dbconfig.json");

var app = new App();
var database = new Database(dbConfig);
var routes = new Routes(app, database);

// Use routes.

这样做有很多好处:


  • 它迫使您将系统分为具有明确依赖关系的组件,而不是将依赖关系隐藏在文件中间的某个地方,它们称为 require( databaseSingleton)或更糟糕的是, global.database

  • 它使单元测试非常容易:如果我要测试路由,我可以使用伪造的 app 数据库注入它参数并仅测试 Routes 代码本身。

  • 它将所有对象图形布线放到一个位置,即组成根目录(在本例中为 server.js ,即应用程序入口点)。这使您可以在一个单一的位置查看系统中所有事物的融合情况。

  • It forces you to separate your system into components with clear dependencies, instead of hiding the dependencies somewhere in the middle of the file where they call require("databaseSingleton") or worse, global.database.
  • It makes unit testing very easy: if I want to test Routes in isolation, I can inject it with fake app and database params and test only the Routes code itself.
  • It puts all your object-graph wiring together in a single place, namely the composition root (which in this case is server.js, the app entry point). This gives you a single place to look to see how everything fits together in the system.

对此,我有一个更好的解释已经见过对Mark Seeman的采访,这是一本出色的著作 Dependency Injection in的作者。 NET 。它同样适用于JavaScript,尤其是Node.js: require 通常用作经典的服务定位器,而不仅仅是模块系统。

One of the better explanations for this that I've seen is an interview with Mark Seeman, author of the excellent book Dependency Injection in .NET. It applies just as much to JavaScript, and especially to Node.js: require is often used as a classic service locator, instead of just a module system.

这篇关于将公共变量传递到Node.js中单独的模块中的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆