当前位置: 代码网 > it编程>前端脚本>Node.js > 在Node.js中执行解压缩文件操作方法

在Node.js中执行解压缩文件操作方法

2024年11月25日 Node.js 我要评论
一、解压文件1.安装依赖:安装adm-zip依赖包:npm installadm-zip --save安装iconv-lite依赖包:npm installiconv-lite --save解压前的f

一、解压文件

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 解压缩文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com