javascript - 导出的对象在 nodejs 中未定义
问题描述
我在 index.js 中使用 multer,我需要在其他路由中使用具有 multer 存储引擎的对象。所以我已经导出了该对象,但问题是当我尝试在未定义的路由文件中使用它时。
index.js
const storage = new GridFsStorage({//some config})
const upload = multer({storage})
app.use('/posts',postRouter)
//if i use the middleware upload.single('file') here, will it affect all the routes like(posts/a,posts/b)?
exports.upload = upload
postRouter.js
const index = require('../index')
setTimeout(() => {
console.log(index.upload)
}, 1000);
console.log(index.upload)
我尝试使用 setTimeout,它给了我预期的结果,但在 settimeout 之外它是未定义的。为什么会这样。通过从索引导出它来在其他一些路由中应用 multer 中间件的最佳方法是什么? 问题是 GridFs 需要一些时间来连接并完成它的工作,但在此之前这个上传对象是 export 的。这就是发生上述情况的原因。知道如何避免这种情况吗?
解决方案
由于GridFsStorage
是异步的,所以它需要一些时间来初始化。您可以将上传作为参数传递给 postRouter 函数。
app.use('/posts', postRouter(upload))
推荐阅读
- sql-server - 使用 Azure Data Studio 编写数据库脚本
- laravel - Laravel Passport 自定义密码验证
- javascript - 用JS创建一个关闭按钮?
- ms-access - 无法保存为 .ACCDE 文件(无法使用
; 文件已在使用) - active-directory - 纯 ldap 查询来搜索设置了 DONT_EXPIRE_PASSWORD 标志的 useraccountcontrol
- c - C中点数组的括号位置之间的差异
- java - How to get a List from string from List of Map with Java 8 Stream?
- c - 无法从自定义 AXI 外设寄存器读取数据
- arm - 刚买了STM32F446,但STM32IDE没有达到我的预期
- javascript - Vanilla JS - 通过单击按钮隐藏和显示 div 的功能