Home > front end >  Read data from DB and send it as a downloadable zip file
Read data from DB and send it as a downloadable zip file

Time:08-25

I have a usecase where I want to read data from database and send it to frontend as a downloadable zip file. I am stuck on how to achieve this using node js and express. For now I was trying to send just a downloadable json file and was confused how to achieve it.

What I have tried so far ->

const data = db.read() // fetch an array of objects.
const myBuffer = Buffer.from(JSON.stringify(data));  //creating a buffer
const readableStream = Readable.from(myBuffer);
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=\"my json file.json\"');
readableStream.pipe(res);

trying this from postman gives me json directly. My question is how to create a downloadable zip file of data here and send it to client. I want to make sure I don't use fs to write a file on server and then send it. Any help and guide would be great, Thanks!!

CodePudding user response:

As @ardritkrasniqi suggested to use a third party npm package, I was able to make an in memory zip file and send it to client using npm package archiver.

I created it like this ->

const data = db.read() // fetch an array of objects.
const myBuffer = Buffer.from(JSON.stringify(data));  //creating a buffer
const archive = archiver.create('zip', {});
archive.append(myBuffer, { name: 'test.json'});
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', 'attachment; filename=\"test.zip\"');
archive.pipe(res);
archive.finalize();

Hope this will be helpful for others who are trying to achieve the same.

PS. I am using express as my backend node framework.

  • Related