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 npm包管理的配置方法及常用命令介绍
Jun 05 NodeJs
nodejs实现HTTPS发起POST请求
Apr 23 NodeJs
nodejs通过phantomjs实现下载网页
May 04 NodeJs
nodejs redis 发布订阅机制封装实现方法及实例代码
Dec 15 NodeJs
nodejs开发——express路由与中间件
Mar 24 NodeJs
详解Nodejs之静态资源处理
Jun 05 NodeJs
nodejs实现解析xml字符串为对象的方法示例
Mar 14 NodeJs
nodeJs爬虫的技术点总结
May 13 NodeJs
nodejs基础之buffer缓冲区用法分析
Dec 26 NodeJs
详解Nodejs get获取远程服务器接口数据
Mar 26 NodeJs
用Nodejs实现在终端中炒股的实现
Oct 18 NodeJs
分享五个Node.js开发的优秀实践 
Apr 07 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
PHP header()函数使用详细(301、404等错误设置)
2013/04/17 PHP
基于xcache的配置与使用详解
2013/06/18 PHP
PHP将session信息存储到数据库的类实例
2015/03/04 PHP
Swoole扩展的6种模式深入详解
2021/03/04 PHP
jquery 注意事项与常用语法小结
2010/06/07 Javascript
理解javascript正则表达式
2016/03/08 Javascript
一种基于浏览器的自动小票机打印实现方案(js版)
2016/07/26 Javascript
一个简单的JavaScript Map实例(分享)
2016/08/03 Javascript
jQuery内容过滤选择器用法示例
2016/09/09 Javascript
AngularJS中directive指令使用之事件绑定与指令交互用法示例
2016/11/22 Javascript
原生js实现查询天气小应用
2016/12/09 Javascript
canvas绘制七巧板
2017/02/03 Javascript
完美实现js选项卡切换效果(一)
2017/03/08 Javascript
用javascript获取任意颜色的更亮或更暗颜色值示例代码
2017/07/21 Javascript
express如何使用session与cookie的方法
2018/01/30 Javascript
JavaScript表格隔行变色和Tab标签页特效示例【附jQuery版】
2019/07/11 jQuery
JS函数进阶之prototy用法实例分析
2020/01/15 Javascript
[02:37]2015国际邀请赛选手档案—LGD.Xiao8
2015/07/28 DOTA
[03:54]Ehome出征西雅图 回顾2016国际邀请赛晋级之路
2016/08/02 DOTA
详解Python中内置的NotImplemented类型的用法
2015/03/31 Python
python类:class创建、数据方法属性及访问控制详解
2016/07/25 Python
使用sklearn之LabelEncoder将Label标准化的方法
2018/07/11 Python
python+pyqt5实现KFC点餐收银系统
2019/01/24 Python
python中嵌套函数的实操步骤
2019/02/27 Python
python sklearn常用分类算法模型的调用
2019/10/16 Python
Pandas实现DataFrame按行求百分数(比例数)
2019/12/27 Python
python属于软件吗
2020/06/18 Python
Python Matplotlib简易教程(小白教程)
2020/07/28 Python
Python实现对word文档添加密码去除密码的示例代码
2020/12/29 Python
《唯一的听众》教学反思
2014/02/20 职场文书
2015年保送生自荐信
2015/03/24 职场文书
2015年销售部工作总结范文
2015/04/27 职场文书
接收函
2019/04/22 职场文书
vue3使用vue-router的完整步骤记录
2021/06/20 Vue.js
详解在OpenCV中如何使用图像像素
2022/03/03 Python
spring IOC容器的Bean管理XML自动装配过程
2022/05/30 Java/Android