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

 更新时间:2019年11月26日 08:27:22   作者:昀赛  
这篇文章主要介绍了nodejs中使用archive压缩文件的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

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的地址

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

相关文章

  • 详解Puppeteer 入门教程

    详解Puppeteer 入门教程

    本篇文章主要介绍了详解Puppeteer 入门教程,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • 如何用Node写页面爬虫的工具集

    如何用Node写页面爬虫的工具集

    这篇文章主要介绍了如何用Node写页面爬虫的工具集,主要介绍了三种方法,分别是Puppeteer、cheerio和Auto.js,感兴趣的小伙伴们可以参考一下
    2018-10-10
  • node使用mysql获取数据库数据中文乱码问题的解决

    node使用mysql获取数据库数据中文乱码问题的解决

    这篇文章主要介绍了node使用mysql获取数据库数据中文乱码问题的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • Express框架定制路由实例分析

    Express框架定制路由实例分析

    这篇文章主要介绍了Express定制路由,结合实例形式分析了express框架定制路由原理、用法及相关注意事项,需要的朋友可以参考下
    2023-05-05
  • 卸载安装Node.js与npm过程详解

    卸载安装Node.js与npm过程详解

    这篇文章是根据自己的经验及实际操作介绍nodejs和npm的卸载及安装,相信对很多人会有帮助,有需要的可以参考学习。
    2016-08-08
  • npm install --save 、--save-dev 、-D、-S 的区别与NODE_ENV的配置方法

    npm install --save 、--save-dev 、-D、-S&nb

    这篇文章主要介绍了npm install --save 、--save-dev 、-D、-S 的区别与NODE_ENV的配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-08-08
  • Node.js 的模块知识汇总

    Node.js 的模块知识汇总

    node.js中是通过模块来划分为单位来划分所有功能的。每个模块为一个js文件。每个模块中定义的全局变量或函数的作用范围也被限制在这个模块中,只能用exports对象将其传递到外部。
    2017-08-08
  • Nodejs探秘之深入理解单线程实现高并发原理

    Nodejs探秘之深入理解单线程实现高并发原理

    这篇文章主要介绍了Nodejs单线程实现高并发原理,对Node.js感兴趣的同学,可以参考下
    2021-04-04
  • 使用socket.io制做简易WEB聊天室

    使用socket.io制做简易WEB聊天室

    这篇文章主要为大家详细介绍了使用socket.io制做简易WEB聊天室,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • window10系统下nvm详细安装步骤以及使用

    window10系统下nvm详细安装步骤以及使用

    nvm可以管理不同版本的node和npm,可以简单操作node版本的切换、安装、查看等,下面这篇文章主要给大家介绍了关于window10系统下nvm详细安装步骤以及使用的相关资料,需要的朋友可以参考下
    2022-07-07

最新评论