Reputation: 25
I'm new to node.js, can anyone help me with my code. the code below can write the query result into 'public/out.csv' file on the server end, but it downloads an empty into the client end. I have no cue why is that.
function ouputCSV(data, filename){
return new Promise(function(resolve, reject){
console.log('writes the results into csv file');
const ws = fs.createWriteStream('public/'+filename+'.csv');
fastcsv.write(data, {headers: true, delimiter:'\t'})
.pipe(ws);
var filepath = ws.path;
resolve(filepath);
})
con.query(sql, function(err, result){
if (err) throw err;
var filename = ('out');
var promise = ouputCSV(result,filename);
promise.then(function(file){
res.download(file);
})
})
Upvotes: 0
Views: 590
Reputation: 12542
if fastcsv
is a stream then you need to wait for it to write to your file completely then resolve
it.
according to fast-csv documentation you can do this:
const rows = [
[ 'a', 'b' ],
[ 'a1', 'b1' ],
[ 'a2', 'b2' ],
];
csv.writeToPath(path.resolve(filepath), rows)
.on('error', err => console.error(err))
.on('finish', () => {
console.log('Done writing.')
resolve(filepath);
});
Or you can resolve
on end
event.
fastcsv.write(data, {headers: true, delimiter:'\t'})
.pipe(ws);
var filepath = ws.path;
fastcsv.on('end', ()=> resolve(filepath));
Upvotes: 1