我正在使用sas js http://sailsjs.org/#!documentation并且我想响应一个csv文件,因为db查询有点像这样: module.exports = { csv: function (req, res) { Model.query("select * from somewhere ", function(err, list){ if (err) c
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: {} };
这是真的吗?
我已经尝试过了:
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; }); }
但那包括“解析”,“_ 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: {} }