如何在Node.js中执行解压缩文件操作

一、解压文件

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文件代码,方法一:(解压文件中文件名包含中文推荐使用)

代码中的:

javascript 复制代码
entry.entryName = iconv.decode(entry.rawEntryName, 'utf8');

可以替换成(二选一)

javascript 复制代码
entry.entryName = iconv.decode(entry.rawEntryName, 'gbk');

文件的路径可以写绝对路径也可以写相对路径,绝对路径不容易错,相对路径是depresssFile.js文件到update-1.0.2.zip解压文件的位置

javascript 复制代码
// 引入依赖
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文件代码,方法二:

javascript 复制代码
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.压缩文件代码:(压缩文件的文件路径对应自己要压缩的文件夹路径即可,存放压缩文件的文件路径同理)

javascript 复制代码
// 压缩文件成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;

压缩完成的目录结构:

相关推荐
w3296362711 天前
飞书接单到月度结算:我用一个 DSH 插件跑通鞋类采购 WMS,附 22 项验收
pdf·node.js·飞书·后端开发·ai agent
濮水大叔2 天前
Cabloy/Vona 为什么不需要 NestJS 的 Dynamic Module
typescript·node.js·nestjs
匠云创新2 天前
读完一万段要两分钟:我们把标书读取从 WPS 对象模型搬到了 docx 解析
性能优化·node.js
某哈压力大2 天前
SSH 突然 Connection reset?不是密钥坏了,是 OpenSSL 把 sshd 干趴了
前端·node.js·命令行
回眸&啤酒鸭2 天前
【回眸】Node.js 新手从零到一实战指南
node.js
浪遏2 天前
recruitment-cli:让 AI 接手求职招聘,从架构到一次发送超时
架构·typescript·node.js
沉默小管4 天前
我用 NestJS + Nuxt 3 做了个导航站,聊几个踩过的坑
node.js·seo
非优秀程序员5 天前
第02章 杭电的英语老师与一台服务器|《互联网产品恩仇录》
数据库·node.js·代码规范
Hone5 天前
juejin-skills 系列 ②:我把「看掘金热榜」也做成了 Agent 技能
开源·node.js·ai编程
w16635 天前
零 Root 无 PC:我让 AI 在手机上把鸿蒙 HDC 协议的底裤扒了下来
node.js