【问题标题】:Unzip .gz with zlib & async/await (w/o using streams)使用 zlib 和 async/await 解压缩 .gz(不使用流)
【发布时间】:2021-03-21 07:45:45
【问题描述】:

由于 zlib 已添加到 node.js,我想问一个关于使用 async/await 样式解压缩 .gz 的问题,不使用 streams,一一进行。

在下面的代码中,我使用fs-extra 而不是标准的fs & typescript(而不是js),但至于答案,它是否有jsts 代码并不重要。

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)
  }
})()

就目前而言,我有这个基于流的代码,它正在工作,但在各种 StackOverflow 答案中,我没有找到任何 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

我知道这个任务会阻塞主线程。对我来说没问题,因为我写了一个简单的日程安排脚本。

【问题讨论】:

    标签: javascript node.js zlib


    【解决方案1】:

    似乎我已经弄明白了,但我仍然不是百分百确定,这里是完整 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-11
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多