Ale*_*Dim 7 javascript zlib node.js
由于zlib已经添加到node.js中,我想问一个关于使用样式解压缩的问题.gz,async/await不使用using streams,一一解压。
在下面的代码中,我使用的fs-extra是而不是标准fs&打字稿(而不是js),但至于答案,它是否具有js或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)
}
})()
Run Code Online (Sandbox Code Playgroud)
就目前而言,我有这段基于流的代码,它正在工作,但在各种 StackOverflow 答案中,我还没有找到任何示例async/await,只有这个,但我猜它也使用流。
那么这可能吗?
//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
Run Code Online (Sandbox Code Playgroud)
我知道这个任务会阻塞主线程。这对我来说没问题,因为我写了一个简单的日程安排脚本。
似乎我已经弄清楚了,但我仍然不是百分百确定,这里是完整 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)
}
})()
Run Code Online (Sandbox Code Playgroud)
如果一个目录中有许多文件,我想您可以并行await Promise.all(files.map => fn())运行此任务。另外,就我而言,我需要解析 JSON,因此请记住JSON.parse.