1

I'm using koajs as a framework for nodejs. I try to create csv data and response it to client but not working

let fields = ['code', 'status'];
let p = new Promise((resolve, reject) => {
    json2csv({data: data, fields: fields }, (err, response) => {
        if (err) {
            reject(err);
        } else {
            resolve(response);
        }
    });
});
return p.then(data => {
    let fileName = 'promotioncode-' + moment().unix();
    ctx.response.attachment(fileName + '.csv');
    ctx.response.type = 'application/ms-excel';
    ctx.body = data;
})

The response is plan text data instead of attachment file Here is response headers

Here is response body

Chu Văn Nam
  • 121
  • 2
  • 5

2 Answers2

4

If you would like to send a downloadable file attached to the body you need to create a read stream of the file.

const fs = require('fs');

ctx.set('Content-disposition', `attachment; filename=${result}`);
ctx.statusCode = 200;
ctx.body = fs.createReadStream(result);

Note: in result you have the file path

davidev
  • 314
  • 9
  • 22
  • I perfomed your idea but received next error: "Error: ENAMETOOLONG: name too long [here all the CSV string that i expect to download]". My filename is "products.csv" – Martin Larizzate Oct 25 '20 at 00:25
1

This worked for me:

ctx.set('Content-disposition', `attachment; filename=${fileName}.csv`);
ctx.statusCode = 200;
ctx.body = data;
realplay
  • 2,078
  • 20
  • 32