writeStream完成后该如何做?

时间:2018-10-07 13:52:18

标签: javascript node.js axios fs request-promise

下载并提取zip文件后,需要返回一个对象。

示例代码:

return rp(distantFile)
.pipe(fs.createWriteStream("./temp/" + zipName))
.on('close', async function () {
    console.log('File written!');
    try {
        // Extraction
        await extract("./temp/" + zipName,
           { dir: "./public/subs/" + name },
           async function (err) {
              // extraction is complete. make sure to handle the err
              if (err) console.log(err)
              console.log("Extraction done!");

              // Remove .zip in /temp once extracted
              await rimraf('./temp/' + zipName,
                  { disableGlob: true },
                  function(){
                     /* do nothing */ 
                  });

              const movieSubs = {
                  language: lang,
                  directory: "/subs/" + name + "/" + name + '.vtt'
              };

              return movieSubs;

          })
     }
     catch(ex) {
         console.log(err)
     }
})

console.log(movieSubs) 上,它向我显示了具有一堆属性的流对象。因此,似乎writeStream尚未关闭。

宁愿使用axios来做,但不知道如何做。

1 个答案:

答案 0 :(得分:0)

我假设langnamerp()的范围内,如果这样:

尝试将其包装在承诺中:

/* with name and lang in scope */
function test(name, lang){
  return new Promise((resolve, reject) =>
    rp(distantFile)
      .pipe(fs.createWriteStream("./temp/" + zipName))
      .on('close', async function () {
        ...
        const movieSubs = {
                  language: lang,
                  directory: "/subs/" + name + "/" + name + '.vtt'
              };
        resolve(movieSubs);
      }
  );
}

test().then(val => console.log('MOVIE_SUBS: ', val));