Skip to content

Instantly share code, notes, and snippets.

@Zubad
Created April 8, 2020 06:37
Show Gist options
  • Save Zubad/048995acfe510ab2807742a02d229e9c to your computer and use it in GitHub Desktop.
Save Zubad/048995acfe510ab2807742a02d229e9c to your computer and use it in GitHub Desktop.
NodeJS: Send response as stream (XLSX File)
// https://stackoverflow.com/questions/61013208/how-to-write-xls-file-and-stream-to-response-in-node-js
const fs = require('fs');
const server = require('http').createServer();
const XLSX = require('xlsx');
server.on('request', (req, res) => {
const data = [
{id: '1', name: 'abc'},
{id: '2', name: 'xyz'}
];
const wb = XLSX.utils.book_new(); // create workbook
const ws = XLSX.utils.json_to_sheet(data); // convert data to sheet
XLSX.utils.book_append_sheet(wb, ws, 'users_sheet'); // add sheet to workbook
const filename = "users.xlsx";
const wb_opts = {bookType: 'xlsx', type: 'binary'}; // workbook options
XLSX.writeFile(wb, filename, wb_opts); // write workbook file
const stream = fs.createReadStream(filename); // create read stream
stream.pipe(res); // send to client
});
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment