Created
September 12, 2023 10:44
-
-
Save sethsandaru/1cbfe0eba39812bbcb19e56b84f5fe2e to your computer and use it in GitHub Desktop.
ExpressJS CSV download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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