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


Posted in NodeJs onNovember 18, 2019

前几天在维护一个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() 函数 readStream 参数中获取的属性值,而 entry.uncompressedSize 也是函数的 entry 参数中获取的属性。接着找 pumpFileDataReadStream() 函数是从哪里调用的。

通过输出日志得出 pumpFileDataReadStream() 函数是在以下面的代码中被调用的:

ZipFile.prototype.addFile = function(realPath, metadataPath, options) {
 var self = this;
 metadataPath = validateMetadataPath(metadataPath, false);
 if (options == null) options = {};
 var entry = new Entry(metadataPath, false, options);
 self.entries.push(entry);
 fs.stat(realPath, function(err, stats) {
  if (err) return self.emit("error", err);
  if (!stats.isFile()) return self.emit("error", new Error("not a file: " + realPath));
  // 这里是文件的大小
  entry.uncompressedSize = stats.size;
  if (options.mtime == null) entry.setLastModDate(stats.mtime);
  if (options.mode == null) entry.setFileAttributesMode(stats.mode);
  entry.setFileDataPumpFunction(function() {
   // readStream在这里创建的
   var readStream = fs.createReadStream(realPath);
   entry.state = Entry.FILE_DATA_IN_PROGRESS;
   readStream.on("error", function(err) {
    self.emit("error", err);
   });
   // 在这里被调用
   pumpFileDataReadStream(self, entry, readStream);
  });
  pumpEntries(self);
 });
};

从上面代码可以看出来 entry.uncompressedSize 是stats.size,即文件的大小, readStream 是创建的文件流。但是在什么情况下两者会不一样呢?感觉只可能在文件还没有读取完,但是是什么原因导致这种情况发生?由于对JS接触的时间不长,没有进行深入分析。最后在抛出异常的上面一行用 console.log 将两个属性的大小值都输出,代码如下所示:

if (entry.uncompressedSize == null) {
   entry.uncompressedSize = uncompressedSizeCounter.byteCount;
} else {
 // 增加日志输出
 console.log("entry size: " + entry.uncompressedSize + ", uncompressedSize: " + uncompressedSizeCounter.byteCount);
 if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", new Error("file data stream has unexpected number of bytes"));
}

在 archive.finalize() 时和 output 写入流的 close 事件时(详细参照官方的示例代码),分别加上日志输出,代码如下所示:

archive.finalize().then(() => {
 // 到这里认为是压缩完成,进行后续处理,实际并没有,参照后面分析
 console.log("finalize");
 // anotherProcess();
}).catch(err => {
  // 压缩出现异常
});
output.on('close', function() {
 console.log('close');
 // 这个业务函数与上面finalize函数中的是互斥,不会同时存在
 anotherProcess();
});

最后分别将 anotherProcess() 函数加到两个异步回调中执行,发现在 close 事件执行时,两个size输出的大小一致,都是文件的大小。而在 finalize 场景测试发现 uncompressedSize 要小于文件的大小。最后将 anotherProcess() 函数放在 close 事件回调函数中执行,问题解决。

总结

以上所述是小编给大家介绍的Nodejs使用archiver-zip-encrypted库加密压缩文件时报错,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

NodeJs 相关文章推荐
将nodejs打包工具整合到鼠标右键的方法
May 11 NodeJs
nodejs实现黑名单中间件设计
Jun 17 NodeJs
如何正确使用Nodejs 的 c++ module 链接到 OpenSSL
Aug 03 NodeJs
nodejs实现HTTPS发起POST请求
Apr 23 NodeJs
NodeJS的Promise的用法解析
May 05 NodeJs
详解NodeJs支付宝移动支付签名及验签
Jan 06 NodeJs
详解nodejs微信公众号开发——4.自动回复各种消息
Apr 11 NodeJs
NodeJS实现微信公众号关注后自动回复功能
May 31 NodeJs
深入解析nodejs HTTP服务
Jul 25 NodeJs
Nodejs 复制文件/文件夹的方法
Aug 24 NodeJs
Mac 安装 nodejs方法(图文详细步骤)
Oct 30 NodeJs
NodeJs 文件系统操作模块fs使用方法详解
Nov 26 NodeJs
NodeJs crypto加密制作token的实现代码
Nov 15 #NodeJs
Nodejs技巧之Exceljs表格操作用法示例
Nov 06 #NodeJs
NodeJS http模块用法示例【创建web服务器/客户端】
Nov 05 #NodeJs
nodejs实现UDP组播示例方法
Nov 04 #NodeJs
nodejs dgram模块广播+组播的实现示例
Nov 04 #NodeJs
Nodejs实现图片上传、压缩预览、定时删除功能
Oct 25 #NodeJs
nodejs语言实现验证码生成功能的示例代码
Oct 13 #NodeJs
You might like
php实现图片以base64显示的方法
2016/10/13 PHP
magento后台无法登录解决办法的两种方法
2016/12/09 PHP
js获取元素到文档区域document的(横向、纵向)坐标的两种方法
2013/05/17 Javascript
js 剪切板的用法(clipboardData.setData)与js match函数介绍
2013/11/19 Javascript
浅析jQuery(function(){})与(function(){})(jQuery)之间的区别
2014/01/09 Javascript
使用AngularJS中的SCE来防止XSS攻击的方法
2015/06/18 Javascript
详解Bootstrap按钮
2016/01/04 Javascript
JS中frameset框架弹出层实例代码
2016/04/01 Javascript
原生js编写autoComplete插件
2016/04/13 Javascript
基于HTML+CSS+JS实现增加删除修改tab导航特效代码
2016/08/05 Javascript
js 两个日期比较相差多少天的实例
2017/10/19 Javascript
vue cli webpack中使用sass的方法
2018/02/24 Javascript
使用vue.js在页面内组件监听scroll事件的方法
2018/09/11 Javascript
基于vue+echarts 数据可视化大屏展示的方法示例
2020/03/09 Javascript
JQuery实现折叠式菜单的详细代码
2020/06/03 jQuery
nodejs中内置模块fs,path常见的用法说明
2020/11/07 NodeJs
[04:53]DOTA2英雄基础教程 祈求者
2014/01/03 DOTA
Python脚本实现下载合并SAE日志
2015/02/10 Python
Python读取Excel表格,并同时画折线图和柱状图的方法
2018/10/14 Python
Pycharm无法显示动态图片的解决方法
2018/10/28 Python
对Django 转发和重定向的实例详解
2019/08/06 Python
tensorflow如何批量读取图片
2019/08/29 Python
使用python和pygame制作挡板弹球游戏
2019/12/03 Python
python MultipartEncoder传输zip文件实例
2020/04/07 Python
TensorFlow的reshape操作 tf.reshape的实现
2020/04/19 Python
HTML5 Canvas 实现K线图的示例代码
2019/12/23 HTML / CSS
2014年小学元旦活动方案
2014/02/12 职场文书
教师应聘自荐信范文
2014/03/14 职场文书
剪彩仪式主持词
2014/03/19 职场文书
纪念九一八事变演讲稿:忘记意味着背叛
2014/09/14 职场文书
给女朋友道歉的话大全
2015/01/20 职场文书
大学生党员个人总结
2015/02/13 职场文书
销售员自我评价
2015/03/11 职场文书
MySQL七种JOIN类型小结
2021/10/24 MySQL
PYTHON基于Pyecharts绘制常见的直角坐标系图表
2022/04/28 Python
MySQL sql模式设置引起的问题
2022/05/15 MySQL