Skip to content

Instantly share code, notes, and snippets.

@Alek-S
Last active November 17, 2017 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alek-S/b9423078713a80731e7590274899eac6 to your computer and use it in GitHub Desktop.
Save Alek-S/b9423078713a80731e7590274899eac6 to your computer and use it in GitHub Desktop.
Send CSV to client of in-memory data, without writing CSV on the server
// will generate CSV from in-memory data
// client will download as CSV without server having to save the file
//requries json2csv from npm
//ref: https://stackoverflow.com/questions/45922074/node-express-js-download-file-from-memory-filename-must-be-a-string
const json2csv = require('json2csv'); //from NPM
const stream = require('stream'); //Native Node
/*
Stuff
*/
let result = json2csv({
data: data,
fields: [
"Header1",
"Header2",
"Header3"
]
});
let fileContents = Buffer.from(result);
let readStream = new stream.PassThrough();
readStream.end(fileContents);
res.set('Content-disposition', 'attachment; filename=' + 'roll.csv');
res.set('Content-Type', 'text/csv; charset=UTF-8');
readStream.pipe(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment