Node.js 从database/config读取目录路径并作为静态HTTP路径公开(nodejs-express)
我正在使用nodejs和express进行服务器端开发。我需要将存储库公开为静态路径。此存储库路径不是硬编码的,并且存储在数据库中。我有从数据库读取配置的方法。当我使用除app.js以外的其他地方时,这很有效。下面是我的示例代码 从数据库读取配置密钥并作为静态HTTP公开的代码:Node.js 从database/config读取目录路径并作为静态HTTP路径公开(nodejs-express),node.js,express,Node.js,Express,我正在使用nodejs和express进行服务器端开发。我需要将存储库公开为静态路径。此存储库路径不是硬编码的,并且存储在数据库中。我有从数据库读取配置的方法。当我使用除app.js以外的其他地方时,这很有效。下面是我的示例代码 从数据库读取配置密钥并作为静态HTTP公开的代码: // for configuration var AppUtilities = require('./server/utilities/AppUtilities'); app.configure(function()
// for configuration
var AppUtilities = require('./server/utilities/AppUtilities');
app.configure(function() {
// set up our express application. Only showing the code related to static HTTP
app.use('/files', express.static(AppUtilities.appConfig.filesRepositoryPath)); //Expose repository as static content
});
app.listen(port);
AppUtilities.js
var documentOperationModule = require('./../persistence/DocumentOperation');
var constants = require("./../utilities/Constants");
//load application config from database and export as module.
documentOperationModule.getAllDocuments(constants.APPLICATION_CONFIG_COLLECTION, function(err, result) {
if (!err) {
console.log("loaded value from app config collection");
exports.appConfig = result[0];
} else {
//throw error
return new Error("Unable to load app config data error >> " + err);
}
});
当我尝试启动nodejs时,出现以下错误
TypeError: Cannot read property 'filesRepositoryPath' of undefined
我对nodejs是新手。如果我无法澄清我的查询,请提供帮助并让我知道。问题在于
getAllDocuments()
函数调用是异步的,因此需要()AppUtilities.js之后才能完成
解决方案是传入回调,类似于:
// AppUtilities.js
var documentOperationModule = require('./../persistence/DocumentOperation');
var constants = require("./../utilities/Constants");
exports.loadAppConfig = function(cb) {
documentOperationModule.getAllDocuments(constants.APPLICATION_CONFIG_COLLECTION, function(err, result) {
if (!err) {
console.log("loaded value from app config collection");
exports.appConfig = result[0];
cb();
} else
cb(new Error("Unable to load app config data error >> " + err));
});
};
// Main entry point
var AppUtilities = require('./server/utilities/AppUtilities');
AppUtilities.loadAppConfig(main);
function main(err) {
if (err)
throw err;
app.configure(function() {
app.use('/files', express.static(AppUtilities.appConfig.filesRepositoryPath));
});
app.listen(port);
}
导出应位于外部,并发布可用函数。然后可以调用module.function。编译器在你的app utilities.js上找不到函数定义。你的定义在另一个未公开的函数中。我无法理解。你能分享一下示例代码吗?谢谢。成功了:-)谢谢你解释了根本原因。