【问题标题】:Using module within module in NodeJS在 NodeJS 的模块中使用模块
【发布时间】:2017-10-27 03:06:41
【问题描述】:

我对 nodejs 还很陌生。编写我的第一个应用程序。我很习惯 php。

为了保持代码的组织和整洁,我总是在单独的文件中编写函数,并根据需要将它们包含在 php 中。

但是,在 nodejs 中,我必须像需要模块一样需要它们。 例如。

functions.js

module.exports = {
check_db : function(key){

},

check_cache : function(key){
    memcached.get(key,function(err, data){
        console.log(data);
    });
},

};

像这样包含在主应用程序中

// Establish connection with cache and database
const mysql = require('mysql2');
const Memcached = require('memcached');
const memcached = new Memcached('localhost:11211');
const bb = require('bot-brother');

//Load the database cache functions
const dbc = require("./functions");
dbc.check_cache(123);

现在我可以从主应用程序文件中访问 dbc 中的函数,但我无法从函数文件中使用主应用程序中所需的模块。 我收到未定义 memcached 的错误。

我该如何解决这个问题?

【问题讨论】:

标签: javascript node.js module memcached require


【解决方案1】:

简单的解决方案,您可以在functions.js 文件中require("memcached") 并在此处创建服务器。但我不会采用这种解决方案,因为如果您在其他地方需要 memcache,您会在 memcache 服务器上打开许多连接。

IMO 的另一个更简洁的解决方案是将 memcache 依赖项 注入您的服务(或称为 functions)。 (这种做法称为依赖注入,如果您想了解它以及它有什么好处)

下面是它的工作原理:

  • 您仍然在主文件中创建 memcache 连接;
  • 不是在functions.js 中导出原始 json 对象,而是导出一个带参数的函数(此处为 memcache
  • 在您的主文件中,您需要该函数并调用它以获取您想要的服务。

下面是代码的样子:

main.js

//Load the database cache functions
const dbcFactory = require("./functions");
const dbc = dbcFactory(memcached)

functions.js

module.exports = function (memcached) {
  return {
    check_db : function(key){},

    check_cache : function(key){
      memcached.get(key,function(err, data){
        console.log(data);
      })
    }
};

【讨论】:

  • 从长远来看,依赖注入是不是有点不干净,你可能不得不传递越来越多的依赖关系?
  • DI(依赖注入)的主要好处是一切都是明确的,并且您拥有的每个服务都易于测试(您可以在测试环境中注入模拟的依赖项)。我想说的是,如果您的代码与 DI 混淆,则表明您的一般架构存在问题,您可能需要重新考虑某些部分:)
  • 它需要你多写一点代码,这是真的,但明确性肯定会改变你的代码的可读性和可理解性
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 2012-12-24
  • 2013-02-08
  • 2014-06-06
相关资源
最近更新 更多