How to return a promise when writestream finishes?

You’ll want to use the Promise constructor:

function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filePath);
    for (const row of arr) {
      file.write(row + "\n");
    }
    file.end();
    file.on("finish", () => { resolve(true); }); // not sure why you want to pass a boolean
    file.on("error", reject); // don't forget this!
  });
}

Leave a Comment