typescript - 等待可读流 ES8 TypeScript 的完成,fs
问题描述
我的代码不起作用,因为在下一行执行之前文件尚未解压缩。这是我的解压功能:
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,而不是已流式传输的数据。
解决方案
src.pipe
不返回 Promise 那么你不能等待它。让我们将其转换为 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
});
})
}
推荐阅读
- sql-server - VBA 运行读取文件然后上传到文件到 SQL 表时出现运行时错误 3265
- django - MultipleObjectsReturned at /cart/ get() 返回了多个订单——它返回了 3
- c# - 使用 AutoMapper 通过匹配 ID 映射到列表中的元素
- c# - 无法访问通过 Windows 服务启动的 Rest 服务中的 HEY_CURRENT_USER 环境变量
- azure - 在 Azure 中选择哪种容器服务
- html - 如何使用 svg 和文本内联显示
- mysql - MySQL 中的 INSTR() 可以从索引中受益吗?
- express - 为什么来自axios的响应.then不能改变变量的值
- android-studio - 使用 Android Studio 4.0 时,我还可以使用 JKS 密钥库将应用程序发布到 Google Play 吗?
- pycharm - “=”运算符周围的Pycharm自动空格