In my current project, I am reading data through API and I would like to have multiple files for each device (I have around 100 devices) and for each device, I would like to create .csv
file, write multiple rows to the file (using node csv-write-stream
package) and close the file. Similarly, I would like to do the same operation for each 100 devices. I tried the following code but I am getting an error that:
writing after end
var csvWriter = require('csv-write-stream');
var writer = csvWriter({ headers: ["TimeStamp", "Gas","gw_temp","rh","abrasion","sensor_temp"]});
for(let j=0;j<data.length;j++){
// Create file for each devices
await writer.pipe(fs.createWriteStream(data[j][0] + '.csv',{flags:"a"}));
// Get data through API
await axios.get([API CALL URL].join('/'), getConfig)
.then(async (response) => {
let res = await response.data;
if(res.length!=0){
for (let i = 0; i < res.length; i++) {
// Write data to csv file
await writer.write(res[i]);
}
}
})
.catch((error) => {
if (error.response) {
console.log("Error in response", error.message);
} else {
console.log("Other error", error.message);
}
});
await writer.end();
await console.log("File writing done",data[j][0]);
}
}
It looks like that I am missing a minor thing but I couldn't able to recognize it.
I also refer this link: "Error: write after end" with csv-write-stream
Updated
If I remove the catch
block then it throws the following error:
(node:13264) UnhandledPromiseRejectionWarning: Error: write after end at writeAfterEnd (_stream_writable.js:236:12) at CsvWriteStream.Writable.write (_stream_writable.js:287:5)