一、解压文件
1.安装依赖:
安装adm-zip依赖包:npm install adm-zip --save
安装iconv-lite依赖包:npm install iconv-lite --save
解压前的file文件夹结构:
update-1.0.2.zip压缩包内容:
2.在depresssfile.js文件,解压zip文件代码,方法一:(解压文件中文件名包含中文推荐使用)
代码中的:
entry.entryname = iconv.decode(entry.rawentryname, 'utf8');
可以替换成(二选一)
entry.entryname = iconv.decode(entry.rawentryname, 'gbk');
文件的路径可以写绝对路径也可以写相对路径,绝对路径不容易错,相对路径是depresssfile.js文件到update-1.0.2.zip解压文件的位置
// 引入依赖 const admzip = require('adm-zip'); const iconv = require('iconv-lite'); // 待解压zip文件所在的路径 var file = 'd:/node/locallibrary/file/update-1.0.2.zip'; // 解压后存放的文件夹 var target = 'd:/node/locallibrary/file'; // 方法1:解压zip文件 function decompressfile1(file, target) { const zip = new admzip(file); var zipentries = zip.getentries(); for (var i = 0; i < zipentries.length; i++) { var entry = zipentries[i]; entry.entryname = iconv.decode(entry.rawentryname, 'utf8'); } zip.extractallto(target, true); } // 执行函数 decompressfile1(file, target); // 导出(在其他js文件引用decompressfile函数需要添加以下代码) module.exports = decompressfile1;
解压zip文件代码,方法二:
const admzip = require('adm-zip'); // 待解压zip文件所在的路径 var file = 'd:/node/locallibrary/file/update-1.0.2.zip'; // 解压后存放的文件夹 var target = 'd:/node/locallibrary/file'; // 方法2:解压zip文件 function decompressfile2(file, target) { const zip = new admzip(file); zip.extractallto(target, true); } // 调用 decompressfile2(file, target); // 导出 module.exports = decompressfile2;
解压后的file文件夹结构:
二、压缩文件
1.压缩文件代码:(压缩文件的文件路径对应自己要压缩的文件夹路径即可,存放压缩文件的文件路径同理)
// 压缩文件成zip格式 const admzip = require('adm-zip'); // filepath: 要压缩的文件路径 var filepath = 'd:/node/locallibrary/file/update-1.0.2/route/route.js'; // outputpath: 压缩后的文件路径 var outputpath = 'd:/node/locallibrary/file/route.zip'; // 压缩文件 function compressfile(filepath, outputpath) { const zip = new admzip(); zip.addlocalfile(filepath); zip.writezip(outputpath); } // 调用函数 compressfile(filepath, outputpath); // 导出函数 module.exports = compressfile;
压缩完成的目录结构:
到此这篇关于如何在node.js中执行解压缩文件操作的文章就介绍到这了,更多相关node.js 解压缩文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论