我正在开发一个 MEAN 堆栈项目,并尝试将一组变量从一个 Controller 传递到另一个 Controller 。我当前的方法是为我的 **artworks.js**
Controller 文件导出多个对象:
module.exports = {
Router: router,
artists: distinctArtistsArray
}
路由器对象是传统的 Express 路由器,但 distinctArtistsArray
是我的 MongoDB 数据库中所有艺术家的字符串数组。我有一个在后台运行的异步函数,它时不时地填充 distinctArtistsArray
。然后,该数组被传递到其他地方编写的一些其他函数中,以便在幕后执行一些 NLP 任务。
我希望另一个 Controller 也能够访问这些变量,因为我不想通过对艺术家信息进行重复的异步查询来给我的 MongoDB 带来过度的负载。这是我的另一个 Controller (complete.js
):
router.get("/", (req, res) => {
var ArtworkSearch = require('../controllers/artworks.js');
console.log(ArtworkSearch.artists)
});
我已将 require('../controllers/artworks/js')
放置在回调函数内,因为我想每次都不断地重新导入值请求到达 /complete
端点。
但是,在我的控制台中,我收到一个空数组 ([]
),这就是我初始化 distinctArtistsArray
的数组。仅供引用,我遵循了与此 SO post 中接受的答案相同的方法。关于类似的主题。
如何让我的艺术家列表在 complete.js
Controller 中可用?
最佳答案
问题是 NodeJS 中所需的模块被缓存了。来自 Node 的文档:
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
因此,如果您想要更新的值,则无需再次require
该文件,并且可以将其移至请求回调之外。
您应该导出一个返回数组的函数,如下所示:
module.exports = {
Router: router,
artists: function () {
return distinctArtistsArray
}
}
然后
console.log(ArtworkSearch.artists())
您还可以手动更新代码中的导出值,通过运行以下命令定期更新 distinctArtistsArray
:
module.exports.artists = distinctArtistsArray
每次更新 distinctArtistsArray
时都需要执行此操作。
关于javascript - 在 Node.JS 中导出多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626936/