我有这样一个函数,它创建一个写入流,然后将字符串数组写入文件。我想让它在编写完成后返回一个 Promise。但我不知道如何才能完成这项工作。
function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
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*/});
}
感谢您的任何评论!
Promise
构造函数:
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!
});
}
您需要在操作完成之前返回
Promise
。function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filePath);
arr.forEach(function(row) {
file.write(row + "\n");
});
file.end();
file.on("finish", () => { resolve(true) });
});
}
在最新的 Node.js 版本中,您可以使用流包中的实用函数 finished,如下所示:
import { finished } from 'node:stream/promises';
import { createWriteStream } from 'node:fs';
function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
const file = createWriteStream(filePath);
arr.forEach((row) => file.write(row + "\n"));
file.end();
return finished(file);
}