nodejs中使用archive压缩文件的实现代码


Posted in NodeJs onNovember 26, 2019

前言

archive是一款在nodejs中可以实现跨平台打包的工具

可以将文件压缩为zip或rar格式

是一个比较好用的第三方模块

install

npm install archiver --save

archive github地址:https://github.com/archiverjs/node-archiver

Quick Start

// require modules
var fs = require('fs');
var archiver = require('archiver');

// create a file to stream archive data to.
var output = fs.createWriteStream(__dirname + '/example.zip');
//设置压缩格式为zip
var archive = archiver('zip', {
  zlib: { level: 9 } // Sets the compression level.
});

// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
output.on('close', function() {
  console.log(archive.pointer() + ' total bytes');
  console.log('archiver has been finalized and the output file descriptor has closed.');
});

// This event is fired when the data source is drained no matter what was the data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see:  https://nodejs.org/api/stream.html#stream_event_end
output.on('end', function() {
  console.log('Data has been drained');
});

// good practice to catch this error explicitly
archive.on('error', function(err) {
  throw err;
});
// pipe archive data to the file
archive.pipe(output);
// append a file from stream
var file1 = __dirname + '/file1.txt';
archive.append(fs.createReadStream(file1), { name: 'file1.txt' });

// append a file from string
archive.append('string cheese!', { name: 'file2.txt' });
// append a file from buffer
var buffer3 = Buffer.from('buff it!');
archive.append(buffer3, { name: 'file3.txt' });

// append a file
archive.file('file1.txt', { name: 'file4.txt' });

// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory('subdir/', 'new-subdir');

// append files from a sub-directory, putting its contents at the root of archive
archive.directory('subdir/', false);

// append files from a glob pattern
archive.glob('subdir/*.txt');

// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
archive.finalize();

实际使用

实际使用中情况可能会比较多

需要打包的源文件一般为远程文件,比如某一个第三方的文件存放地址,这时则需要先将第三方文件下载到本地

示例方法,可以根据实际需要修改相应的参数

function download(files){
  //下载文件的本地存档地址
  //示例 files = [{name: 'xxxx.js',url:'https://xx/xx/xxxx.js'}]
  let dirPath = path.resolve(__dirname, '文件存放的本地位置')
  mkdir(dirPath);

  let tmps = files.map((item,index) => {
    let stream = fs.createWriteStream(path.resolve(dirPath, item.name));

  return new Promise((resolve,reject)=>{
    try {
      request(item.url).pipe(stream).on("close", function (err) {
        console.log("文件[" + item.name + "]下载完毕");

        resolve({
          url: path.resolve(dirPath, item.name),
          name: item.name
        })
      });
    } catch (e) {
      reject(e||'')
    }
  })
});

return new Promise((res,rej)=>{
  Promise.all(tmps).then((result) => {
    console.log(result)
    res(result)
  }).catch((error) => {
    console.log(error||'')
  })
})
}

//创建文件夹目录
function mkdir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
    console.log("文件夹创建成功");
  } else {
    console.log("文件夹已存在");
  }
}

将下载到本地的文件打包为一个zip文件,可以参照 Quick Start 中的api组合使用

// append files from a sub-directory, putting its contents at the root of archive
 archive.directory('subdir/', false);
 //要注意第二个参数false,这个参数代表打包后的文件相对于output的目录结构,不写这个参数代表按照第一个参数('subdir/')的目录层级

打包之后的文件位置是在本地位置,此时在推送到前端页面中下载url需要组装成http或https的地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

NodeJs 相关文章推荐
nodejs分页类代码分享
Jun 17 NodeJs
NodeJS学习笔记之网络编程
Aug 03 NodeJs
nodejs中操作mysql数据库示例
Dec 20 NodeJs
深入理解Nodejs Global 模块
Jun 03 NodeJs
nodejs后台集成ueditor富文本编辑器的实例
Jul 11 NodeJs
Windows下使用Nodejs运行js的方法
Sep 02 NodeJs
nodejs调取微信收货地址的方法
Dec 20 NodeJs
使用nodejs+express实现简单的文件上传功能
Dec 27 NodeJs
nodejs使用redis作为缓存介质实现的封装缓存类示例
Feb 07 NodeJs
Nodejs 和 Electron ubuntu下快速安装过程
May 04 NodeJs
CentOS7中源码编译安装NodeJS的完整步骤
Oct 13 NodeJs
NodeJS多种创建WebSocket监听的方式(三种)
Jun 04 NodeJs
NodeJS实现一个聊天室功能
Nov 25 #NodeJs
Nodejs使用archiver-zip-encrypted库加密压缩文件时报错(解决方案)
Nov 18 #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
You might like
在线短消息收发的程序,不用数据库
2006/10/09 PHP
一个SQL管理员的web接口
2006/10/09 PHP
PHP7 弃用功能
2021/03/09 PHP
JavaScript接口实现代码 (Interfaces In JavaScript)
2010/06/11 Javascript
JS操作select下拉框动态变动(创建/删除/获取)
2013/06/02 Javascript
Node.js的包详细介绍
2015/01/14 Javascript
javascript动态创建链接的方法
2015/05/13 Javascript
基于jQuey实现鼠标滑过变色(整行变色)
2015/12/07 Javascript
JS实现简单的右下角弹出提示窗口完整实例
2016/06/21 Javascript
AngularJS实现在ng-Options加上index的解决方法
2016/11/03 Javascript
JavaScript数据结构中栈的应用之表达式求值问题详解
2017/04/11 Javascript
Three.js利用orbit controls插件(轨道控制)控制模型交互动作详解
2017/09/25 Javascript
薪资那么高的Web前端必看书单
2017/10/13 Javascript
JS实现面向对象继承的5种方式分析
2018/07/21 Javascript
支付宝小程序自定义弹窗dialog插件的实现代码
2018/11/30 Javascript
vue-test-utils初使用详解
2019/05/23 Javascript
记录vue做微信自定义分享的一些问题
2019/09/12 Javascript
Vue分页效果与购物车功能
2019/12/13 Javascript
JS+JQuery实现无缝连接轮播图
2020/12/30 jQuery
python实现查找excel里某一列重复数据并且剔除后打印的方法
2015/05/26 Python
在java中如何定义一个抽象属性示例详解
2017/08/18 Python
解决python中 f.write写入中文出错的问题
2018/10/31 Python
python如何实现复制目录到指定目录
2020/02/13 Python
matplotlib 曲线图 和 折线图 plt.plot()实例
2020/04/17 Python
Django2.1.7 查询数据返回json格式的实现
2020/12/29 Python
《两个铁球同时着地》教学反思
2014/02/13 职场文书
初中新生军训方案
2014/05/13 职场文书
物联网工程专业推荐信
2014/09/08 职场文书
社区班子个人对照检查材料思想汇报
2014/10/07 职场文书
医药公司开票员岗位职责
2015/04/15 职场文书
Node实现搜索框进行模糊查询
2021/06/28 Javascript
详解CSS3.0(Cascading Style Sheet) 层叠级联样式表
2021/07/16 HTML / CSS
一篇文章带你深入了解Mysql触发器
2021/08/02 MySQL
使用refresh_token实现无感刷新页面
2022/04/26 Javascript
Python tensorflow卷积神经Inception V3网络结构
2022/05/06 Python
阿里面试Nacos配置中心交互模型是push还是pull原理解析
2022/07/23 Java/Android