首页 > 语言 > JavaScript > 正文

Nodejs使用archiver-zip-encrypted库加密压缩文件时报错(解决方案)

2024-05-06 15:43:53
字体:
来源:转载
供稿:网友

前几天在维护一个nodejs写的命令行工具,要增加一个压缩zip文件时加密码功能。压缩文件时使用了 archiver 库,加密码使用了 archiver-zip-encrypted 库。在windows系统上测试时,发现会概率的出现以下异常:

events.js:174 throw er; // Unhandled 'error' event ^Error: file data stream has unexpected number of bytes at ByteCounter. (xxx/node_modules/yazl/index.js:162:99) at ByteCounter.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1103:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at ByteCounter. (xxx/node_modules/yazl/index.js:162:85) at ByteCounter.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1103:12) at process._tickCallback (internal/process/next_t

我的本机环境是:

npm:6.9.0
node: v10.16.3

在另外一个同事的windows系统上测试,他那边是上面异常必现,对应的node版本是v10.15。

具体使用的代码不贴了,基本上是参照官方 demo 来写的,压缩完成最后调用代码如下所示:

archive.finalize().then(() => {  // 到这里认为是压缩完成,进行后续处理,实际并没有,参照后面分析  anotherProcess();}).catch(err => {  // 压缩出现异常处理...});

出现异常后一一检查代码和官方demo不一样的地方,并没有发现什么异常之处,网上搜索也没有发现这种异常记录。由于刚接触JS,不是很熟,就从问题开始下手,找到出现问题的代码,开始调试。

错误日志中提示是在 yzal/index.js 文件中发生异常,找到出现异常的代码如下所示:

function pumpFileDataReadStream(self, entry, readStream) { var crc32Watcher = new Crc32Watcher(); var uncompressedSizeCounter = new ByteCounter(); var compressor = entry.compress ? new zlib.DeflateRaw() : new PassThrough(); var compressedSizeCounter = new ByteCounter(); readStream.pipe(crc32Watcher)      .pipe(uncompressedSizeCounter)      .pipe(compressor)      .pipe(compressedSizeCounter)      .pipe(self.outputStream, {end: false}); compressedSizeCounter.on("end", function() {  entry.crc32 = crc32Watcher.crc32;  if (entry.uncompressedSize == null) {   entry.uncompressedSize = uncompressedSizeCounter.byteCount;  } else {   // 异常从这里抛出来的   if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", new Error("file data stream has unexpected number of bytes"));  }  entry.compressedSize = compressedSizeCounter.byteCount;  self.outputStreamCursor += entry.compressedSize;  writeToOutputStream(self, entry.getDataDescriptor());  entry.state = Entry.FILE_DATA_DONE;  pumpEntries(self); });}

从上面代码可以看出来: uncompressedSizeCounter.byteCount 是从 pumpFileDataReadStream()

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表