导出的对象在 nodejs 中未定义

exported object is undefined in 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 需要一些时间来连接并完成它的工作,但在此之前导出此上传对象。这就是为什么会出现上述情况。知道如何避免这种情况吗?

由于GridFsStorage是异步的,所以需要一些时间来初始化。你可以 将上传作为参数传递给 postRouter 函数。

app.use('/posts', postRouter(upload))