3

I want update file in zip arhive with nodejs. For example i have zip file with two files:

 a.zip
   |-a.txt
   |-b.txt 

I use archiver:

var archiver = require('archiver');
var archive = archiver('zip', {});
archive.pipe(fs.createWriteStream('./a.zip'));
archive.append(fs.createReadStream('./c.txt'), { name: 't.txt' });
archive.finalize();

But I have a problem, my archive is completely overwritten. As a result, I get:

 a.zip
   |-t.txt

If I use:

archive.file('./a.txt', { name: 't.txt' });

the result remains the same. And I want to get this structure as a result

 a.zip
   |-a.txt
   |-b.txt
   |-t.txt

Or update the contents of one of the files a.txt or b.txt

alex10
  • 2,726
  • 3
  • 22
  • 35

2 Answers2

3

Appending to an existing archive is currently not possible with archiver. Here's the relevant issue opened in 2013: support appending to existing archives #23

In your case, append is appending to the stream, not to whatever was at the destination of the new file. archiver doesn't care about what's at a.zip, it just overwrites it with whatever you give to archiver.append.

It seems like your best bet would be to unzip the existing file with maxogden/extract-zip, then append the results to the new version of the archive with archiver.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Mattias Martens
  • 1,369
  • 14
  • 16
0

You can use JSZip. You can refer to the official documentation.

And here's a simple Node.js example:

var fs = require("fs");
var JSZip = require("jszip");

async function zipDemo() {
    // read the existing zip file
    var zipData = fs.readFileSync("input.zip");
    var zip = await JSZip.loadAsync(zipData);
    // add a new JSON file to the zip
    zip.file("sample.json", JSON.stringify({demo:123}));
    // write out the updated zip
    zip.generateNodeStream({type:'nodebuffer', streamFiles:true})
    .pipe(fs.createWriteStream('output.zip'))
    .on('finish', function () {
        console.log("output`enter code here`.zip written.");
    });
}

zipDemo();
Henry Luo
  • 354
  • 4
  • 10