Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV response on sails js

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"

like image 593
dpineda Avatar asked Feb 12 '23 19:02

dpineda


2 Answers

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: {}
}
like image 191
dpineda Avatar answered Feb 15 '23 11:02

dpineda


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();
       }
   }
};
like image 36
Binu Paul Avatar answered Feb 15 '23 12:02

Binu Paul