Last active
September 3, 2021 15:19
-
-
Save orpheousff8/78237d6e716e7a13dd7b12ba84e05927 to your computer and use it in GitHub Desktop.
Node server response in CSV format
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 { Parser } = require('json2csv') | |
//example database model (Modeling MongoDB with Mongoose) | |
const Log = require('../models/logModel') | |
const responseCsv = async (req, res) => { | |
let logs | |
try { | |
//reading logs from the database | |
//append .lean() to get a plain JS object rather than a mongoose document; use less memory | |
logs = await Log.find({}, '_id voltage current temperature loggedAt').sort({ | |
loggedAt: -1, | |
}).lean() | |
} catch (err) { | |
//error because of database reading | |
console.log(err) | |
res.status(500).json({ message: err.message }) | |
return | |
} | |
//csv field labels, the parser will re-arrange you data (logs) into the order below | |
const fields = [ | |
{ label: 'time', value: 'loggedAt' }, | |
{ label: 'id', value: '_id' }, | |
{ label: 'voltage', value: 'voltage' }, | |
{ label: 'current', value: 'current' }, | |
{ label: 'temperature', value: 'temperature' }, | |
] | |
const json2csv = new Parser({ fields: fields }) | |
try { | |
const csv = json2csv.parse(logs) | |
} catch (err) { | |
//error because of parsing error | |
console.log(err) | |
res.status(500).json({ message: err.message }) | |
} | |
//the filename, can be anything | |
res.attachment('data.csv') | |
//response with the csv data | |
res.status(200).send(csv) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment