我的代码不能工作,因为在下一行执行之前,文件没有被解压。这是我的解压函数:
import { createGunzip } from 'zlib';
import { createReadStream, statSync, createWriteStream } from 'fs';
function fileExists(filePath: string) {
try {
return statSync(filePath).isFile();
} catch (err) {
return false;
}
}
async function gunzipFile(source: string, destination: string): Promise<void> {
if (!fileExists(source)) {
console.error(`the source: ${source} does not exist`);
return;
}
const src = createReadStream(source);
const dest = createWriteStream(destination);
await src.pipe(createGunzip())
.pipe(dest)
.on('error', (error) => {
// error logging
})
.on('end', () => {
return;
});
}我如何重构它才能让它异步地正常工作?或非异步(如果它将等待完成)。还有类似的问题,但它们对我不起作用,可能是因为这个函数返回void,而不是已经流式传输的数据。
发布于 2021-11-02 01:28:07
src.pipe没有返回一个承诺,那么你就不能等待它。让我们将其转换为Promise:
function gunzipFile(source: string, destination: string): Promise<void> {
if (!fileExists(source)) {
console.error(`the source: ${source} does not exist`);
return;
}
const src = createReadStream(source);
const dest = createWriteStream(destination);
return new Promise((resolve, reject) => { // return Promise void
src.pipe(createGunzip())
.pipe(dest)
.on('error', (error) => {
// error logging
// reject(error); // throw error to outside
})
.on('finish', () => {
resolve(); // done
});
})
}https://stackoverflow.com/questions/69798101
复制相似问题