Nathan Nathan - 5 months ago 27
Node.js Question

Rename files inside zip archive in nodejs

I am writing a nodejs script which should do the following:


  1. Download a zip file

  2. Remove the top level directory of the zip file (moving all files one folder up)

  3. Upload the new zip file



Because the zip file is rather large, I would like to rename (or move) the files without unzipping and rezipping the file.

Is that possible?

Answer

Yes, it's possible Using a library like 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 

Algorithm

Create a newZip object to temporarily hold files in memory Read all entries in the downloaded zip. For each entry

  1. Read the fileName. This includes the path
  2. Read the file content using the fileName
  3. Remove the top level directory name to get the newFileName
  4. Add the fileContent in step 2 to the newZip giving it the newFileName from step 3
  5. Finally, write out the newZip to disk giving it a new zipName

Hope that helps

Comments