I want to wrap the following code in asyn function and await the content written into the file:
const fs = require("fs");
const { stringify } = require("csv-stringify");
const db = require("./db");
const filename = "saved_from_db.csv";
const writableStream = fs.createWriteStream(filename);
const columns = [
"year_month",
"month_of_release",
"passenger_type",
"direction",
"sex",
"age",
"estimate",
];
const stringifier = stringify({ header: true, columns: columns });
db.each(`select * from migration`, (error, row) => {
if (error) {
return console.log(error.message);
}
stringifier.write(row);
});
stringifier.pipe(writableStream);
console.log("Finished writing data");
The function must resolve when the content has been written into the file.
But how can I detect that event?
I added event listeners on both the stringifier
and the writableStream
but non had been called
stringifier.on('close', ()=> console.log( `STR CLOSED`))
stringifier.on('finish', ()=> console.log( `STR FINISH`))
writableStream.on('close', ()=> console.log( `WS CLOSED`))
writableStream.on('finish', ()=> console.log( `WS FINISH`))
Example taken from here