在nodejs中重命名zip存档内的文件

Nat*_*han 6 zip node.js

我正在编写一个nodejs脚本,它应该执行以下操作:

  1. 下载 zip 文件
  2. 删除 zip 文件的顶级目录(将所有文件向上移动一个文件夹)
  3. 上传新的 zip 文件

由于 zip 文件相当大,我想重命名(或移动)文件而不解压缩和重新压缩文件。

那可能吗?

Vit*_*lis 4

是的,可以使用像adm-zip这样的库

var AdmZip = require('adm-zip');

//create a zip object to hold the new zip files
var newZip = new AdmZip();

// reading archives
var zip = new AdmZip('somePath/download.zip');
var zipEntries = zip.getEntries(); // an array of ZipEntry records

zipEntries.forEach(function(zipEntry) {
    var fileName = zipEntry.entryName;
    var fileContent = zip.readAsText(fileName)
    //Here remove the top level directory
    var newFileName = fileName.substring(fileName.indexOf("/") + 1);

    newZip.addFile(newFileName, fileContent, '', 0644 << 16);        
});

newZip.writeZip('somePath/upload.zip');  //write the new zip 
Run Code Online (Sandbox Code Playgroud)

算法

创建一个 newZip 对象来临时将文件保存在内存中 读取下载的 zip 中的所有条目。对于每个条目

  1. 读取文件名。这包括路径
  2. 使用fileName读取文件内容
  3. 删除顶级目录名称以获取 newFileName
  4. 将步骤 2 中的 fileContent 添加到 newZip 中,并为其提供步骤 3 中的 newFileName
  5. 最后,将 newZip 写入磁盘并为其指定新的 zipName

希望有帮助