Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

795
Views
Descomprima .gz con zlib y async/await (sin usar flujos)

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 console

Entiendo que esta tarea bloqueará el hilo principal. Está bien para mí, ya que escribo un script simple de programación de días.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!