Skip to content

Instantly share code, notes, and snippets.

@Tonel
Last active October 14, 2022 14:51
Show Gist options
  • Save Tonel/9714fea0fc8b5d0383d98cac0ed6f6f4 to your computer and use it in GitHub Desktop.
Save Tonel/9714fea0fc8b5d0383d98cac0ed6f6f4 to your computer and use it in GitHub Desktop.
const express = require("express")
const app = express()
app.get("/users/getCSV", function (req, res) {
// retrieving the user with a query...
const users = [
{ name: "Patricia", surname: "Smith", age: null },
{ name: "John", surname: null, age: 56 },
{ name: "Maria", surname: "Brown", age: 37 },
]
// initializing the CSV string content with the headers
let csvData = ["name", "surname", "age"].join(",") + "\r\n"
users.forEach((user) => {
// populating the CSV content
// and converting the null fields to ""
csvData += [user.name, user.surname, user.age].join(",") + "\r\n"
})
// returning the CSV content via the "users.csv" file
res
.set({
"Content-Type": "text/csv",
"Content-Disposition": `attachment; filename="users.csv"`,
})
.send(csvData)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment