如何在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;

压缩完成的目录结构:

相关推荐
Bdygsl14 小时前
Node.js(1)—— Node.js介绍与入门
node.js
Java 码农15 小时前
nodejs koa留言板案例开发
前端·javascript·npm·node.js
胡gh16 小时前
浏览器:我要用缓存!服务器:你缓存过期了!怎么把数据挽留住,这是个问题。
前端·面试·node.js
ccnocare19 小时前
Node.js ZIP 安装
node.js
码上有料1 天前
Node.js中XLSX库的实践使用指南
node.js
前端老鹰1 天前
Node.js 网页解析神器:cheerio 模块实战指南,像 jQuery 一样玩转 HTML
后端·node.js
Hilaku1 天前
前端需要掌握多少Node.js?
前端·javascript·node.js
前端工作日常1 天前
我的 SSR 测试 入门之旅
前端·node.js
前端双越老师1 天前
【干货】Nodejs + Deepseek 开发 MCP Server 和 Client 踩坑记录
人工智能·node.js·deepseek
叫我阿柒啊2 天前
Java全栈工程师面试实战:从基础到微服务的深度解析
java·redis·微服务·node.js·vue3·全栈开发·电商平台