Nodejs writes zip file from base64

I am writing the base64

encoded value to a zip file. The following code I'm using to write:

var base64Data  =   base64_encoded_value;
base64Data  +=  base64Data.replace('+', ' ');
binaryData  =   new Buffer(base64Data, 'base64').toString('binary');

fs.writeFile('test.zip', binaryData, "binary", function (err) {
    console.log(err); // writes out file without error
});

      

A working file and file is created test.zip

, then the problem occurs when I extract it, which gives me the following error:

End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of /home/user/Node/project/public/media/written/zip4045508057.zip or
        /home/user/Node/project/public/media/written/zip4045508057.zip.zip, and cannot find /home/user/Node/project/public/media/written/zip4045508057.zip.ZIP, period.

      

Is there a way to do this ???

+3


source to share


2 answers


You will need to convert base64 to utf8 format. Then you can use this converted data to write the file.

Try using the following function to convert base64 to utf8



/**
 * @param b64string {String}
 * @returns {Buffer}
 */
function _decodeBase64ToUtf8(b64string) {
    var buffer;
    if (typeof Buffer.from === "function") {
        // Node 5.10+
        buffer = Buffer.from(b64string, 'base64');
    } else {
        // older Node versions
        buffer = new Buffer(b64string, 'base64');
    }

    return buffer;
}

      

I used this to create a ZIP file using base64 data

+1


source


An alternative way to extract the .zip file from the base64 string is to use the npm package mws-extract-document



const mwsExtract = require('mws-extract-document');

const dist = './folder/to/document.zip';
const base64String = ''; //located at PdfDocument data response from MWS api.

// PROMISE
mwsExtract(base64String, dist)
          .then((msg)=>{
            // file saved. do something here...
            console.log(msg);
          })
          .catch(err)=>{
            console.log(err);
          });

      

0


source







All Articles