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

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

问题描述

我使用单独的路由器文件作为主应用程序和身份验证应用程序的模块.我无法获得将变量(db 客户端)传递到路由器的最佳方法.我不想对其进行硬编码或将其传递给:

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) {

也许最好的方法是使用单例寄存器或使用全局数据库变量?

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.
  • 它使单元测试变得非常简单:如果我想单独测试 Routes,我可以用假的 appdatabase 参数注入它并仅测试 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 的采访,优秀著作.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天全站免登陆