node.js - 如何在 node.js 中捕获 zlib 错误

标签 node.js exception-handling zlib

我正在从可能被压缩的服务器下载内容,所以我使用了我在不同地方找到的这个样板文件:

    var file = fs.createWriteStream(filename);
    var request = https.get(url, function(response) {
        switch (response.headers['content-encoding']) {
        case 'gzip':
            response.pipe(zlib.createGunzip()).pipe(file);
            break;
        case 'deflate':
            response.pipe(zlib.createInflate()).pipe(file);
            break;
        default:
            response.pipe(file);
            break;
        }
        file.on('finish', function() {
            console.log("Done: "+url);
            file.close(function() {});
        });
    }).on('error', function(err) { // Handle errors
        fs.unlink(filename, function() {});
        console.log(err+" "+url);
    });

问题是,如果 HTTPS 请求因网络错误而失败,我有时会抛出此异常:

Error: unexpected end of file
  at Zlib._handle.onerror (zlib.js:363:17)

异常未被该“错误”事件处理程序捕获。那么我如何捕获它,以便我可以正确清理文件并知道重试?

最佳答案

您有与请求相关的错误处理程序,但没有与解压缩和保存文件相关的错误处理程序。 try catch 解压流中的错误:

var decompressed;
switch (response.headers['content-encoding']) {
case 'gzip':
    decompressed = response.pipe(zlib.createGunzip());
    break;
case 'deflate':
    decompressed = response.pipe(zlib.createInflate());
    break;
default:
    decompressed = response;
    break;
}
decompressed.on('error', function(err) {
    // handle error
});
decompressed.pipe(file);

要阅读更多内容,请遵循此答案 - Error handling with node.js streams

关于node.js - 如何在 node.js 中捕获 zlib 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439074/

相关文章:

javascript - 如何更改数据库/文件二进制路径?

node.js - EADDRINUSE - 仍然无法终止 Node 进程

java - 如何循环用户输入直到输入整数?

powershell - 无法在 Powershell 脚本中捕获 ADException

php - 字符串在膨胀后包含许多 '\0'

node.js - 如何使用 Node.JS 在 MongoDB 中使用 $inc 运算符作为变量

javascript - 使用 Promise 和循环?

c++ - std::current_exception 是否应该从类的析构函数中的 catch block 返回非空

c++ - 如何使用 zlib.h 解压缩 m MYSQL_RES 中的 COMPRESSED BLOB,而不在 mysql 查询中使用 UNCOMPRESS

c++ - 使用 zlib 解压缩 .zip 文件的简单方法