Search code examples
javascriptjszip

How to replace contents of file in a zip using JSzip?


I have been working on a project, I download a zip file from internet through XMLHttpRequest (type: blob ) and then I try to read its content using JSzip.So every zip has a json which I am interested in say manifest.json. So I was successful to read it with this code.

var read_zip = new JSZip();
res=xhr.response;
read_zip.loadAsync(xhr.response).then(function (zip) {
return zip.file("manifest.json").async("string");
}).then(function (text) {
obj = JSON.parse(text);
console.log(text);});

after this I made some changes to 'obj', Now I want to replace the existing manifest with this modified 'obj' json contents and save it. I was trying this code

 var write_zip = new JSZip();
 write_zip.loadAsync(xhr.response).then(function (zip) {
 zip.file("manifest.json" , obj) ;
 zip.generateAsync({type:"blob"})
 .then(function (blob) {
 saveAs(blob, "hello.zip");
 });});

but I am getting this error

 Uncaught (in promise) Error: Can't read the data of 'manifest.json'. 
 Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) 
 ?

sorry, I am new to this.


Solution

  • It looks like you're trying to write an object into zip which is not supported. According to the documentation on JsZip the value to be written needs to be of type:

    String/ArrayBuffer/Uint8Array/Buffer/Blob/Promise/Nodejs stream

    See: JSZip#file(name, data [,options])