首页 > 解决方案 > 导出的对象在 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 的。这就是发生上述情况的原因。知道如何避免这种情况吗?

标签: javascriptnode.jsnode-modulesmulter

解决方案


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

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

推荐阅读