如何避免Node js中强大的函数尽早返回

问题描述 投票:0回答:1

我使用以下代码在节点js中上载和读取文件。它可以按预期工作,但方法会提前返回。在那里,在发生“ fileBegin”和“ file”事件之前返回该方法。您能否告诉我,我需要更改什么才能使其仅在上传和处理文件后才返回?

const form = new formidable.IncomingForm();

form.parse(req);
form.on('fileBegin', async function (name, file) {
...............

});
form.on('file', async function (name, file) {
...............

})
.on("end", function () {
...............
});

}
......................
......................
......................

 return "Success"
}
node.js formidable
1个回答
0
投票

使用中间件

const fs = require('fs')
const fileType = require('file-type')
const multiparty = require('multiparty')
const uploadMiddleware = (request, response, next) => {
      if (request.method !== 'POST') {
        next()
        return
      }

      const form = new multiparty.Form()
      form.parse(request, async (error, fields, files) => {
        if (error) throw new Error(error);

         //  const file = files.file[0]
          // const buffer = fs.readFileSync(file.path)
          // request.file = your file 

          next()
        } catch (error) {
          return response.status(400).send(error)
        }
      })
    }
app.post('/upload', multipartUpload, yourController)
© www.soinside.com 2019 - 2024. All rights reserved.