【问题标题】:How to wait until a file finishes writing before using it?如何等到文件完成写入后再使用它?
【发布时间】:2020-11-22 07:44:38
【问题描述】:
我正在创建一个 png 文件,但是当我尝试使用它时,它会在完成编写之前尝试这样做
如何让它等到文件完成写入后再使用它?
PImage.encodePNGToStream(img, fs.createWriteStream('template.out.png'));
channel.send("Drawn By: "+req.body["Drawer"], { files: ["./template.out.png"] });
【问题讨论】:
标签:
node.js
discord.js
fs
【解决方案1】:
根据PImage-docs encodePNGToStream 是异步的并返回一个promise。所以你必须await 或使用then(...)。
例如
await PImage.encodePNGToStream(img, fs.createWriteStream('template.out.png'));
channel.send("Drawn By: "+req.body["Drawer"], { files: ["./template.out.png"] });
或
PImage.encodePNGToStream(img, fs.createWriteStream('template.out.png')).then(_ => channel.send("Drawn By: "+req.body["Drawer"], { files: ["./template.out.png"] }));