node.js - 推荐将配置传递给模块的方法

标签 node.js design-patterns

将设置变量传递给 Node.js 模块的推荐方法是什么? 目前我正在使用以下设计,需要在 module.exports 函数内放置 require 调用。这样做是为了避免在任何地方使用 var config = require('./myConfig') 因为我们的想法是在应用程序入口点(也称为应用程序.js、服务器.js...)

// A module that needs configuration settings when required.

// Some requires here...
var sample_module1 = require('amodule');
var sample_module2 = require('another_module');


module.exports = function(config) {

var apiKey = config.apiKey; // Get api key from configuration.

// This require must be here because needs 'config' variable...
var apiCaller = require('../lib/api_caller.js')(apiKey);


// An exported function that also uses configuration settings.
exports.makeCall = function(callback) {

  // Get some settings from configuration.
  var text = config.welcomeText; 
  var appName = config.appName; 

  // Use apiCaller module...
  apiCaller.send(appName, text, function(e){
    if (e) { return callback(e); }
    return callback(null);
  });
}

...

return exports;
}

我想知道是否有更好的替代方案来使用“../lib/api_caller.js”模块(通过重构等)

最佳答案

一种解决方案可能是使用类似nconf的东西并依靠它在正确的时间加载正确的文件。特别是在您的情况下,我会使用 default.json 配置文件在项目的根目录中创建一个 conf 文件夹。然后,您可以创建一个利用 nconf 和新创建的文件的全局 configuration.js:

var nconf = require("nconf")
  , path = require("path")
  , environment;

nconf.argv().env("_");

environment = nconf.get("NODE:ENV") || "development";

nconf.file("default", path.resolve("config/default.json"));

module.exports = nconf.get

从需要某些配置的其他模块中,您可以简单地使用:

var conf = require('configuration.js')
conf('NODE_ENV') // print NODE_ENV

但这听起来与您不想要的非常相似。另一种选择是使用类似构造函数的东西:

var ApiCaller = require('../lib/api_caller.js');
var apiCaller = new ApiCaller({ some: 'parameter' });
apiCaller.doSomething();

“类”ApiCaller 看起来像:

function ApiCaller(options){
  this.options = options;
}

Api.prototype.something = function(){
  this.options //my options
};

关于node.js - 推荐将配置传递给模块的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18186955/

相关文章:

javascript - 使用任意 gulpfile 名称运行 gulp(不是 gulpfile.js)

java - DAO 和连接

javascript - 在初始页面加载时通过 Ajax 加载内容的设计模式

javascript - dom 是如何在对象字面量的函数之间缓存的? (Javascript)

node.js - 如何在不编译的情况下在nodejs中使用typescript/flow

javascript - 将带有 NodeJS 循环的 json 对象复制到 JSON 文件中

c# - 如何动态组合条件?

c# - ASP.NET MVP 模式

javascript - 在 javascript/typescript/nodejs 中创建可能的组合

javascript - 后端服务器端使用Nodejs进行动画渲染