How to zip files PDF from a Storage in NodeJS

1.1k Views Asked by At

I need to create a zip file with any PDF what I recieved from Storage AWS, and I am trying do this with ADM-zip in NodeJS, but i cant read the final file.zip. Here is the code.

        var zip = new AdmZip();

                            // add file directly
                            var content = data.Body.buffer;
                            zip.addFile("test.pdf", content, "entry comment goes here");
                            // console.log(content)
                            // add local file
                            zip.addLocalFile(`./tmp/boletos/doc.pdf`);
                            // // get everything as a buffer
                            var willSendthis = zip.toBuffer();
                            console.log(willSendthis)
                            // // or write everything to disk
                            zip.writeZip("test.zip", `../../../tmp/boletos/${datastring}.zip`);

As it is this only creates a .zip for each file..zip

1

There are 1 best solutions below

0
On

I was also facing this issue. I looked through a lot of SO posts. This is how I was able to create a zip with multiple files from download urls. Please keep in mind, I'm unsure this is best practice, or if this is going to blow up memory.

Create a zip folder from a list of id's of requested resources via the client.

const zip = new AdmZip();
  await Promise.all(sheetIds.map(async (sheetId) => {
    const downloadUrl = await this.downloadSds({ sheetId, userId, memberId });
    if (downloadUrl) {
      await new Promise((resolve) => https.get(downloadUrl, (res) => {
        const data = [];
        res.on('data', (chunk) => {
          data.push(chunk);
        }).on('end', () => {
          const buffer = Buffer.concat(data);
          resolve(zip.addFile(`${sheetId}.pdf`, buffer));
        });
      }));
    } else {
      console.log('could not download');
    }
  }));
  const zipFile = zip.toBuffer();

I then used downloadjs in my React.js client to download.

const result = await sds.bulkDownloadSds(payload);
if (result.status > 399) return store.rejectWithValue({ errorMessage: result?.message || 'Error', redirect: result.redirect });
const filename = 'test1.zip';
const document = await result.blob();
download(document, filename, 'zip');