Search code examples
javascriptformattingformatzip

Download base64 encoded zip file I receive from server


I'm receiving a base64 encoded zip file from the server,and I have to save it.

When I first receive the string it looks like this: enter image description here

After that, if I atob(content), it looks like this: enter image description here

Minimal reproducible code that can be run with node:

const fs = require(`fs`)
const fetch = require(`node-fetch`)
const JSZip = require(`jszip`)

function logMainFile(blob){
  const zip = new JSZip();
  zip.loadAsync(blob).then(function(zip) {
    zip.file(`main.py`).async(`string`).then(function (content) {
      console.log(content);
    });
  })
}

async function getFileFromGitlab() {
  const url = `https://gitlab.com/api/v4/projects/47987400/repository/files/products%2Fcuore%2Fcuore.zip?ref=main`

  const text = await fetch(url)
  const data = await text.json()
  const blob = atob(data?.content);

  // This is here just to show the data is there
  logMainFile(blob)

  fs.writeFileSync(`test.zip`, blob)

}

getFileFromGitlab()

The problem is that I can't open the file, it seems to be corrupted. What am I doing wrong?


Solution

  • I found the problem, I just had to transforme it to bytes before saving it. I did that using

    function str2bytes (str: string) {         
        const bytes = new Uint8Array(str.length)         
        for (let i=0; i<str.length; i++) {             
            bytes[i] = str.charCodeAt(i)         
        }         
        return bytes     
    }