Koa2 upload file stream did not finish processing the direct return result?

const router = require("koa-router")();
const fs = require("fs");

router.post("/upload", async (ctx){
    const file = ctx.request.body.files.file;    // 
    const reader = fs.createReadStream(file.path);    // 
    const ext = file.name.split(".").pop();        // 
    const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`);        // 
    reader.pipe(upStream);    //  
    return ctx.body = "";
})

the above code is uploading files, but this paragraph is not understood:

reader.pipe(upStream);    //  
return ctx.body = ""; //

my doubt is: stream takes some time to finish execution, and it is asynchronous. It can be said that here return "upload successfully" , We all know , return is equivalent to ending this http request, so stream

Jul.16,2021

take advantage of the event provided by EventEmitter
and then you can simply write the above code here and encapsulate it like this

.
function getFile (reader, upStream) {
 return new Promise(function (resolve, reject) {
  let stream = reader.pipe(upStream); 
  stream.on('finish', function () {
   console.log('');
  });
 });
}
Menu