【发布时间】:2015-01-29 23:26:38
【问题描述】:
[编辑]
感谢 Stafano 以更好的方式将我的问题正式化: 你有一个模块
-) 这个模块中有几个文件
-) 所有这些文件都依赖于模块本身未知路径的配置
-) 这个模块本身并没有做太多的事情,并且打算被其他应用程序使用
-) 这些应用程序应该在模块使用之前将配置路径注入到模块中
所以我有这个模块,从另一个应用程序中使用。它由其他子模块组成,我想使用配置对象对其进行配置。 我已经尝试在我的子模型中注入配置,但我在原始问题中遇到了同样的问题。
例如我的模块使用 mongoDB (with mongoose) 作为存储。
// app.js
// in the config object i have the URI to the mongo instance (in order to create a connection).
var myModule = require('myModule')(config);
// myModule.js
// files
// myModule/index.js expose the module's functionalities
// is the entry point so I create the mongoose connection
var mongoose = require('mongoose');
module.exports = function(config){
var connection = mongoose.createConnection(config.store.URL);
// I need to expose this connection to the others submodules.
}
// myModule/storeController.js contains the business logic that use the store (createItem, deleteItem, get...) and requrie mongoose and my Models (store in the models folder)
var mongoose = require('mongoose');
var Item = require('./models/item.js');
exports.createItem = function(item){
Item.save(item, function(err, item){
if (err) throw
...
});
}
// myModule/models/item.js
// In this module i need to use the connection application in the configuration.
var mongoose = require('mongoose');
var connection = // i don't know how to get it
var ItemSchema = new mongoose.Schema({
name: String
});
module.exports = mongoose.model('item', ItemSchema);
如果我将配置 obj 注入到 item.js 中,我将无法执行我的模型的 module.exports。 我希望这个例子可以澄清我的问题,但问题很简单,将对象作为参数后暴露。
[上一个] 我有一个需要模块的 node.js 应用程序。此模块接受配置文件路径(JSON 文件)。 我需要在 require 上加载该配置并将其公开给模块。
我怎样才能实现这种行为?
类似:
// app.js
var myModule = require('myModule')(__dirname + '/config/myModuleCnfig.json');
// myModule.js
module.exports = function(configPath){
var config = require(configPath);
module.exports = config; // This is wrong
}
有没有其他方式获取配置路径,配置模块,共享配置?
“共享配置”是指我想让我的模块的其他文件可以使用该配置。
感谢您的任何建议!
【问题讨论】:
-
如果你需要返回配置,为什么不在第一个要求之前将它放在一个变量中,然后将值传递给模块?
-
我可以做到,但我后来也遇到了同样的问题,我找不到一种简单的方法将该配置暴露给我模块的其他文件,例如在配置中我可以有一些东西我在模块的另一个文件中使用,所以我试图使用 require 导出配置。你有什么建议吗??谢谢!
-
我不明白。该模块是完全多余的。相当于只设置 var myModule = require(__dirname + '/config/myModuleCnfig.json');
-
相对路径在 require() 中工作,所以你根本不需要 __dirname。
-
它只是模块的第一行,接受配置文件路径的 index.js,这样做之后我如何将该配置暴露给我模块中的其他文件?示例: // myModule/index.js module.exports = function(config){ //something to share my configuration object } // 我的模块中的另一个文件 myModule/anotherOne.js var configuration = require what?
标签: javascript node.js configuration module