Friday, 23 March 2018
javascript - How to return a promise when writestream finishes?
Answer
Answer
I have such a function, which create a write stream and then write the string array into the file. I want to make it return a Promise once the writing is finished. But I don't know how I can make this work.
function writeToFile(filePath: string, arr: string[]): Promise {
const file = fs.createWriteStream(filePath);
arr.forEach(function(row) {
file.write(row + "\n");
});
file.end();
file.on("finish", ()=>{ /*do something to return a promise but I don't know how*/});
}
Thank you for any comment!
Answer
You'll want to use the Promise
constructor:
function writeToFile(filePath: string, arr: string[]): Promise {
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!
});
}
Subscribe to:
Post Comments (Atom)
casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV
In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...
-
The whole error output being: LNK2019 unresolved external symbol wWinMain referenced in function "int __cdecl __scrt_common_main_seh(vo...
-
I recently used canvas to conert images to webp, using : const dataUrl = canvas.toDataURL('image/webp'); But this takes a lots of ti...
-
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradi...
No comments:
Post a Comment