Skip to content

Instantly share code, notes, and snippets.

@sethsandaru
Created September 12, 2023 10:44
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 sethsandaru/1cbfe0eba39812bbcb19e56b84f5fe2e to your computer and use it in GitHub Desktop.
Save sethsandaru/1cbfe0eba39812bbcb19e56b84f5fe2e to your computer and use it in GitHub Desktop.
ExpressJS CSV download
const express = require('express');
const app = express();
// Sample data in CSV format
const csvData = [
['Name', 'Email'],
['John Doe', 'johndoe@example.com'],
['Jane Smith', 'janesmith@example.com'],
];
// Define a route to trigger the CSV download
app.get('/download-csv', (req, res) => {
// Define the file name and content type
const fileName = 'sample.csv';
res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
res.setHeader('Content-Type', 'text/csv');
// Create a writable stream to the response
const stream = res;
// Write the CSV data to the response
csvData.forEach((row) => {
stream.write(row.join(',') + '\n');
});
// End the response
stream.end();
});
// Start the Express server
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment