Dado que zlib se agregó a node.js, me gustaría hacer una pregunta sobre cómo descomprimir .gz con el estilo async/await , sin usar streams , una por una.
En el siguiente código, estoy usando fs-extra en lugar de fs estándar y mecanografiado (en lugar de js), pero en cuanto a la respuesta, no importa si tendrá código js o 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) } })() Por ahora, tengo este código, basado en flujos, que funciona, pero en varias respuestas de StackOverflow, no he encontrado ningún ejemplo con async/await , solo este , pero supongo que también usa flujos.
Entonces, ¿es posible?
//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 consoleEntiendo que esta tarea bloqueará el hilo principal. Está bien para mí, ya que escribo un script simple de programación de días.
Parece que lo he resuelto, pero todavía no estoy cien por ciento seguro, aquí hay un ejemplo de IIFE completo:
(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) } })() Si tiene muchos archivos en un directorio, supongo que podría usar await Promise.all(files.map => fn()) para ejecutar esta tarea en paralelo. Además, en mi caso, necesitaba analizar JSON, así que recuerdealgunos matices de JSON.parse .