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 相关文章推荐
PHPStorm 2020.1 调试 Nodejs的多种方法详解
Sep 17 NodeJs
Nodejs实现的一个简单udp广播服务器、客户端
Sep 25 NodeJs
轻松创建nodejs服务器(5):事件处理程序
Dec 18 NodeJs
nodejs 整合kindEditor实现图片上传
Feb 03 NodeJs
nodejs微信公众号支付开发
Sep 19 NodeJs
win系统下nodejs环境安装配置
May 04 NodeJs
ubuntu编译nodejs所需的软件并安装
Sep 12 NodeJs
nodejs使用express获取get和post传值及session验证的方法
Nov 09 NodeJs
使用nodeJs来安装less及编译less文件为css文件的方法
Nov 20 NodeJs
Nodejs中crypto模块的安全知识讲解
Jan 03 NodeJs
详解利用nodejs对本地json文件进行增删改查
Sep 20 NodeJs
nodejs开发一个最简单的web服务器实例讲解
Jan 02 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的类树(支持无限分类)
2006/10/09 PHP
一个域名查询的程序
2006/10/09 PHP
PHP简洁函数小结
2011/08/12 PHP
php中jQuery插件autocomplate的简单使用笔记
2012/06/14 PHP
php实现mysql数据库操作类分享
2014/02/14 PHP
下载站控制介绍字数显示的脚本 显示全部 隐藏介绍等功能
2009/09/19 Javascript
eval的两组性能测试数据
2012/08/17 Javascript
js验证输入是否为手机号码或电话号码示例
2013/12/30 Javascript
js中传递特殊字符(+,&)的方法
2014/01/16 Javascript
jQuery Easyui学习之datagrid 动态添加、移除editor
2016/01/27 Javascript
JS模态窗口返回值兼容问题的完美解决方法
2016/05/28 Javascript
js 将图片连接转换成base64格式的简单实例
2016/08/10 Javascript
如何写好你的JavaScript【推荐】
2017/03/02 Javascript
浅谈redux, koa, express 中间件实现对比解析
2019/05/23 Javascript
基于js实现复制内容到操作系统粘贴板过程解析
2019/10/11 Javascript
vue中uni-app 实现小程序登录注册功能
2019/10/12 Javascript
VUE+elementui组件在table-cell单元格中绘制微型echarts图
2020/04/20 Javascript
Taro UI框架开发小程序实现左滑喜欢右滑不喜欢效果的示例代码
2020/05/18 Javascript
python中实现定制类的特殊方法总结
2014/09/28 Python
深度定制Python的Flask框架开发环境的一些技巧总结
2016/07/12 Python
Python中常见的异常总结
2018/02/20 Python
详解通过API管理或定制开发ECS实例
2018/09/30 Python
Python实现手机号自动判断男女性别(实例解析)
2019/12/22 Python
Python如何将图像音视频等资源文件隐藏在代码中(小技巧)
2020/02/16 Python
Python爬虫抓取指定网页图片代码实例
2020/07/24 Python
奥地利票务门户网站:oeticket.com
2019/12/31 全球购物
教师实习自我鉴定
2013/12/13 职场文书
大学生的网上创业计划书
2013/12/31 职场文书
项目合作计划书
2014/01/09 职场文书
2014年大学生自我评价
2014/01/19 职场文书
中学生励志演讲稿
2014/04/26 职场文书
技术入股合作协议书
2014/10/07 职场文书
幼儿园园长安全责任书
2015/05/08 职场文书
妈妈再爱我一次观后感
2015/06/08 职场文书
Go 自定义package包设置与导入操作
2021/05/06 Golang
redis中lua脚本使用教程
2021/11/01 Redis