Search code examples
javascriptnode.jscsvexport-to-csvfeathersjs

How to write and download csv file in feathers api?


I'm trying to create api for export data in csv file using api, which means i want to download csv file using feathers services.

app.service('/csv').hooks({
  before: {
    create: [ function(hook, next) {
        const dataToStore = [
          {
            to: 'marshall',
            from: 'marshall',
            body: 'Stop talking to that rubber ducky!'
          }, {
            to: 'marshall',
            from: 'marshall',
            body: `...unless you're rubber duck debugging.`
          }
        ]
        hook.data = dataToStore;
        next();
      }
    ]
  },
  after: {
    create: [ function(hook,next){
        // here i need imported data to be write in csv and make api side as downloadable 
        // when i hit the service i want to download file in csv file format.
        hook.result.code = 200; 
        next();
      }
    ]
  },
  error: {
    create: [function(hook, next){
      hook.error.errors = { code : hook.error.code };
      hook.error.code = 200;
      next();
    }]
  }
});

Solution

  • Formatting the response is not done in hooks but in an Express middleware either with a general custom formatter or a service specific middleware.

    Add it at the end when registering the /csv service (the service call data will be in res.data):

    const json2csv = require('json2csv');
    const fields = [ 'to', 'from', 'body' ];
    
    app.use('/csv', createService(), function(req, res) {
      const result = res.data;
      const data = result.data; // will be either `result` as an array or `data` if it is paginated
      const csv = json2csv({ data, fields });
    
      res.type('csv');
      res.end(csv);
    });