exported object is undefined in nodejs

I am using multer in index.js and i need to use an object which has multer storage engine in other routes. So i have exported the object but the problem is when i i try to use it in the route file its undefined.

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) 

i tried using setTimeout and its giving me the expected result but outside settimmeout its undefined. why is this happening. what is the best way to apply the multer middleware in some other routes by exporting it from index? the problem is GridFs is taking sometime to connect and do its work, but before that this upload object is exported . thats why above scenario occurs. any idea how to avoid that?

Add Comment
1 Answer(s)

As GridFsStorage is asynchronous, so it need some time to init. And you can just pass upload as param to the postRouter function.

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

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.