2

I have put together the below code that creates a CSV called example.csv, using the json2csv library.

I would prefer to not have to save down and store the CSV file before it is passed to the front end to be downloaded.

I can't seem to figure out how to stream or pipe the file to the front end, without saving it first.

How to take the output CSV file of the json2csv library and send it straight tot he front end?

Some of my code

    const input = new Readable({ objectMode: true });
    input._read = () => {};
    input.push(JSON.stringify(parsed));
    input.push(null);

    var outputPath = "example.csv";
    const output = createWriteStream(outputPath, { encoding: "utf8" });
    const json2csv = new Transform(opts, transformOpts);

    // Pipe to output path
    input.pipe(json2csv).pipe(output);
    
    res.setHeader("Content-Type", "text/csv");
    res.download(outputPath);
tbowden
  • 1,008
  • 1
  • 19
  • 44

1 Answers1

2

You can simply pipe the json2csv stream to the res object, e.g:

const ReadableStream = require('stream').Readable;
const Json2csvTransform = require('json2csv').Transform;

app.get('/csv', (req, res) => {
    const stream = new ReadableStream();
    stream.push(JSON.stringify(data));
    stream.push(null);

    const json2csv = new Json2csvTransform({}, transformOpts);
    res.setHeader('Content-disposition', 'attachment; filename=data.csv');
    res.writeHead(200, { 'Content-Type': 'text/csv' });
    stream.pipe(json2csv).pipe(res);
})
eol
  • 23,236
  • 5
  • 46
  • 64
  • This correctly send the data as a file response. But the headers are named as ['0', '1', '2' ...]. When I set the `fields` attribute from the `Transform opts`, it only send the header row. Any idea on how to correctly add a header to the csv? – buddhiv May 15 '22 at 18:44
  • When I use this method I get an extra quote at the end of my output: id" firstName" displayName" 179 Test1" Test1-179" – insivika Sep 27 '22 at 16:06
  • from where it comes *Json2csvTransform*?? – M. Mariscal Oct 13 '22 at 05:42
  • @M.Mariscal: As described in the question from the package `json2csv`. – eol Oct 13 '22 at 08:35