【问题标题】:Await the Completion of a Readable Stream ES8 TypeScript, fs等待可读流 ES8 TypeScript 的完成,fs
【发布时间】:2021-12-16 06:05:23
【问题描述】:

我的代码无法正常工作,因为在下一行执行之前文件尚未解压缩。 这是我的解压函数:

import { createGunzip } from 'zlib';
import { createReadStream, statSync, createWriteStream } from 'fs';

function fileExists(filePath: string) {
  try {
    return statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
}

async function gunzipFile(source: string, destination: string): Promise<void> {
  if (!fileExists(source)) {
    console.error(`the source: ${source} does not exist`);
    return;
  }
  const src = createReadStream(source);
  const dest = createWriteStream(destination);
  await src.pipe(createGunzip())
    .pipe(dest)
    .on('error', (error) => {
      // error logging
    })
    .on('end', () => {
      return;
    });
}

我将如何重构它以使其异步正常工作?或非异步,如果它会在完成之前等待。有类似的问题,但它们对我不起作用,可能是因为此函数返回 void,而不是已流式传输的数据。

【问题讨论】:

    标签: typescript async-await fs data-stream


    【解决方案1】:

    src.pipe 不返回 Promise 那么你就等不及了。让我们将其转换为 Promise:

    function gunzipFile(source: string, destination: string): Promise<void> {
      if (!fileExists(source)) {
        console.error(`the source: ${source} does not exist`);
        return;
      }
      const src = createReadStream(source);
      const dest = createWriteStream(destination);
    
      return new Promise((resolve, reject) => { // return Promise void
        src.pipe(createGunzip())
          .pipe(dest)
          .on('error', (error) => {
            // error logging
            // reject(error); // throw error to outside
          })
          .on('finish', () => {
            resolve(); // done
          });
      })
    }
    

    【讨论】:

    • 谢谢,这行得通。我需要将 on('end, ...` 更改为 on('finish', ..),但首先这是我的错误。
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2016-02-09
    • 2023-04-07
    • 2013-03-22
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多