3

I've set up a small node js BE app, built with express and fastCsv module on top of it. The desired outcome would be to be able to download a csv file to the client side, without storing it anywhere inside the server, since the data is generated depending on user criteria. So far I've been able to get somewhere it it, Im using streams, since that csv file could be pretty large depending on the user selection. Im pretty sure something is missing inside the code bellow:

const fs = require('fs');
const fastCsv = require('fast-csv');
.....
(inside api request)
.....
router.get('/', async(req, res) => {
   const gatheredData ...

   const filename = 'sometest.csv'
   
   res.writeHead(200, {
       'Content-Type': 'text/csv',
       'Content-Disposition': 'attachment; filename=' + filename
   })

   const csvDataStream = fastCsv.write(data, {headers: true}).pipe(res)

})

The above code 'works' in some way as it does deliver back the response, but not the actual file, but the contents of the csv file, which I can view in the preview tab as a response. To sum up, Im trying to stream in that data, into a csv and push it to download file to client, and not store it on the server. Any tips or pointers are very much appreciated.

RGLSV
  • 2,018
  • 1
  • 22
  • 37
  • 1
    any result on that? – HRK44 Sep 09 '21 at 12:06
  • It looks like you may need to enclose the `filename` part in double quotes like so: `res.header("Content-Disposition", 'attachment; filename="' + filename + '"');` – Benji Feb 20 '22 at 12:20

1 Answers1

0

Here's what worked for me after created a CSV file on the server using the fast-csv package. You need to specify the full, absolute directory path where the output CSV file was created:

const csv = require("fast-csv");
const csvDir = "abs/path/to/csv/dir";
const filename = "my-data.csv";
const csvOutput = `${csvDir}/${filename}`;
console.log(`csvOutput: ${csvOutput}`); // full path

/*
CREATE YOUR csvOutput FILE USING 'fast-csv' HERE
*/

res.type("text/csv");
res.header("Content-Disposition", `attachment; filename="${filename}"`);
res.header("Content-Type", "text/csv");
res.sendFile(filename, { root: csvDir });

You need to make sure to change the response content-type and headers to "text/csv", and try enclosing the filename=... part in double-quotes, like in the above example.

Benji
  • 310
  • 3
  • 12