Search code examples
node.jszipbufferadm-zip

Save zip file represented as a string


im downloading a zip file from the internet. I recieve it using a XHR request (using node-webkit) and this means that the content of the zip comes as a string in xhr.responseText. I now want to save this file to the disk, however, i cant seem to get it saved as a noncurrupted zip archive.

I have basically used fs.writeFile, fs.write, fs.createWriteStream, but I cant seem to get it right.

I am using a node module named AdmZip which accepts a file buffer that then can be saved as a zip archive. So, I guess, this could be one way to go, but how to I make a buffer out the the string that i recieve?

btw: i can't use the http module to recieve the file from the internet due to a bug in node.js, therefore im using the xhr request.


Solution

  • So, I found a soulution, by first and foremost setting the xhr.responseType = 'arraybuffer' and then turning the response into a Uint8Array. From there I converted the Uint8Array to a nodejs buffer which I then could save.

    var arrayBuffer = xhr.response,
        byteArray = new Uint8Array(arrayBuffer);
    
    
    var buffer = new Buffer(byteArray.length);
    
    for (var i = 0; i < byteArray.length; i++) {
    
        buffer.writeUInt8(byteArray[i], i);
    
    }
    
    
    fs.writeFileSync(fname, buffer);