我正在使用nodejs pdfkit创建一个pdf文档,并将其保存在文件中。
我想将我的 pdf 写入文件中,并确保在退出我的函数之前 pdf 已完成写入。
这是我的代码:
export default async function generate_pdf(params, filePath) {
let doc = new PDFDocument({ size: "A4", margin: 50 });
// Filling my pdf document...
fillDoc(doc);
// Finish the document and save it in a file
doc.end();
// Here a fs.WriteStream is created with automatic close.
const writeStream = doc.pipe(fs.createWriteStream(filePath));
// Here I would like to make sure that writeStream has finished before ending the function.
// something like await waitForClose(writeStream);
// before returning
return filePath;
}
我知道根据 WriteStream 文档,有一个事件“close”被发出。
所以我可以这样做:
writeStream.on('close', () => {
// my code
});
但这并不能解决我的需求,因为我可能会同时创建多个文件,我想要一种方法来确保在退出函数之前所有文件都已完成写入。
如果您能提供帮助,请提前致谢:)
我相信你会做这样的事情:
await new Promise(resolve => writeStream.on("close", resolve));