0

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

Hairi
  • 3,318
  • 2
  • 29
  • 68

1 Answers1

0

Capture the pipe, and then listen for the finish event on that:

await new Promise((resolve, reject) => {

  //...all your code here...

  const stream = stringifier.pipe(writableStream);
  stream.on('finish', resolve);
});
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153