Skip to content

Instantly share code, notes, and snippets.

@jeffskelton3
Created March 17, 2015 15:29
Show Gist options
  • Save jeffskelton3/2b9fc748ec69205694dc to your computer and use it in GitHub Desktop.
Save jeffskelton3/2b9fc748ec69205694dc to your computer and use it in GitHub Desktop.
sails.js CSV response type
/**
* 200 (OK) CSV Response
*
* Usage:
* return res.csv(data);
*
* @param {Object} data
* - must be an object array
* @param {String|Object} options
* - columns : column names we want for the CSV must be a string array
*/
module.exports = function sendCsv (data, options) {
// Get access to `req`, `res`, & `sails`
var req = this.req
, res = this.res
, sails = req._sails
, json2csv = require('json2csv')
, fs = require('fs')
, download_dir = '.tmp/downloads/'
, filename = options && options.filename ? options.filename : 'file_' + ((new Date().getTime().toString())) + '.csv'
, fullpath = download_dir + filename;
sails.log.silly('res.csv() :: Sending 200 ("OK") response');
//PUT THE DATA THROGH THE GAUNTLET...
if(!data){
throw new Error('data cannot be null');
}
if(!_.isArray(data)){
throw new Error('data must be of type array');
}
var columns = data.length ? _.keys(data[0]) : [];
// if we made it this far, send the file
// Set status code
res.status(200);
json2csv({data: data, fields: columns}, function(err, csv) {
if (err) { throw err; }
//make the download dir if it doesnt exist
fs.mkdir(download_dir, 0777, function(err){
if(err){
//we dont care if the directory already exists.
if (err.code !== 'EEXIST'){
throw err;
}
}
//create the csv file and upload it to our directory
fs.writeFile(fullpath, csv, function(err) {
if (err) throw err;
sails.log.silly('file saved to ' + fullpath);
res.download(fullpath, filename, function(err){
if(err) {
throw err;
return;
}
//delete the file after we are done with it.
fs.unlink(fullpath);
});
});
});
});
};
@jeffskelton3
Copy link
Author

depends on json2csv node module

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment