I'm using sails js http://sailsjs.org/#!documentation and I want to response a csv file as a result from a db query someting like this:
module.exports = {
csv: function (req, res) {
Model.query("select * from somewhere ", function(err, list){
if (err) console.log(err);
// Send a CSV response
return res.csv(list);
});
},
_config: {}
};
Is this posible?
I already try with:
csv: function (req, res) {
Model.query("select * from somewhere ", function(err, list){
if (err) console.log(err);
var objArray = list;
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
var head = array[0];
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
line = line.slice(0, -1);
str += line + '\r\n';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
line = line.slice(0, -1);
str += line + '\r\n';
}
res.setHeader('Content-disposition', 'attachment; filename=testing.csv');
res.writeHead(200, { 'Content-Type': 'text/csv' });
res.write(str);
return res;
});
}
but that includes "parse","_typeCast"
var json2csv = require('json2csv');
var moment = require('moment');
module.exports = {
csv: function (req, res) {
MyModel.query("select id, name, email from MyModel", function(err, list){
if (err) console.log(err);
// Send a CSV response
var config = {
fields : ['id','name', 'email'],
data: list
};
json2csv(config, function(err, csv) {
if (err) console.log(err);
var filename = "report-" + moment().format("YYYY-MM-DD") + ".csv";
res.attachment(filename);
res.end(csv, 'UTF-8');
});
});
},
_config: {}
}
If using sails 1.0, you can use the following code:
module.exports = {
friendlyName: 'admin_user_export',
description: 'Admin users export to CSV.',
fn: async function (req, res) {
sails.log.debug('ADMIN: user export CSV action');
var users = await User.find({select: ['id', 'first_name', 'last_name', 'email', 'phone']});
const { parse } = require('json2csv');
const fields = ['id', 'first_name', 'last_name', 'email', 'phone'];
const opts = {fields};
if (users) {
try {
const csv = parse(users, opts);
console.log(csv);
this.res.set('Content-Type', 'application/octet-stream');
this.res.attachment('users.csv');
return this.res.send(csv);
} catch (err) {
console.error(err);
}
} else {
return this.res.ok();
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With