Search code examples
javascriptnode.jszipunzip

Zip files in javascript


I have a file in the directory "./Data/Engine/modules/xnc.zip" that I want to unzip to "./Data/Engine/modules/xnc".

After that, I will write to the files and I need to rezip it easily!

I would create my own method but I am not capable of creating a full zip archive zip and unzip the module

Does anyone have any ideas?

Edit: Thanks for all the help! Sadly I can't send questions anymore though :(


Solution

  • you can use nodejs module AdmZip to for zipping and unzipping of files.

    Installation:

    npm install adm-zip
    

    Code:

    const fs = require('fs');
    const AdmZip = require('adm-zip');
    
    
      var zip = new AdmZip(".sample.zip");
      zip.extractEntryTo(/*entry name*/"sample.txt", /*target path*/"D:/stackoverflow", /*maintainEntryPath*/false, /*overwrite*/true);
      fs.appendFileSync('sample.txt', 'data to append');
      zip.addLocalFile('D:/stackoverflow/sample.txt')
      zip.writeZip('D:/stackoverflow/sample.zip')
    

    if you want to remove the unzipped file

    fs.unlinkSync('sample.txt')