Last active
October 14, 2022 14:51
-
-
Save Tonel/9714fea0fc8b5d0383d98cac0ed6f6f4 to your computer and use it in GitHub Desktop.
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() | |
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