使用 zlib 和 async/await 解压 .gz(w/o 使用流)

Unzip .gz with zlib & async/await (w/o using streams)

由于zlib已被添加到node.js我想问一个关于解压缩.gz的问题async/await风格,w/o使用streams,一个接一个。

在下面的代码中,我使用 fs-extra 而不是标准的 fs 和打字稿(而不是 js),但是至于答案,它是否具有 [=20 并不重要=] 或 ts 代码。

import fs from 'fs-extra';
import path from "path";
import zlib from 'zlib';

(async () => {
  try {
    //folder which is full of .gz files.
    const dir = path.join(__dirname, '..', '..', 'folder');
    const files: string[] = await fs.readdir(dir);

    for (const file of files) {
      //read file one by one
      
      const
        file_content = fs.createReadStream(`${dir}/${file}`),
        write_stream = fs.createWriteStream(`${dir}/${file.slice(0, -3)}`,),
        unzip = zlib.createGunzip();

      file_content.pipe(unzip).pipe(write_stream);
    }
  } catch (e) {
    console.error(e)
  }
})()

至于现在,我有这个基于流的代码,它可以工作,但是在各种 Whosebug 答案中,我没有找到任何 async/await 的例子,只有 this one,但是我猜它也使用流。

那有可能吗?

//inside async function
const read_file = await fs.readFile(`${dir}/${file}`)
const unzip = await zlib.unzip(read_file);
//write output of unzip to file or console

I understand that this task will block the main thread. It's ok for me since I write a simple day schedule script.

看来我已经弄明白了,但我仍然不能百分百确定,这里是完整的 IIFE 示例:


(async () => {
  try {
    //folder which is full of .gz files.
    const dir = path.join(__dirname, '..', '..', 'folder');
    const files: string[] = await fs.readdir(dir);

    //parallel run
    await Promise.all(files.map(async (file: string, i: number) => {
      
      //let make sure, that we have only .gz files in our scope
      if (file.match(/gz$/g)) {
        const
          buffer = await fs.readFile(`${dir}/${file}`),
          //using .toString() is a must, if you want to receive readble data, instead of Buffer
          data = await zlib.unzipSync(buffer , { finishFlush: zlib.constants.Z_SYNC_FLUSH }).toString(),
          //from here, you can write data to a new file, or parse it.
          json = JSON.parse(data);

        console.log(json)
      }
    }))
  } catch (e) {
    console.error(e)
  } finally {
    process.exit(0)
  }
})()

如果一个目录中有很多文件,我想您可以并行使用 await Promise.all(files.map => fn()) 到 运行 这个任务。另外,在我的例子中,我需要解析 JSON,所以请记住 some nuances of JSON.parse.