From 0fb26456a0300ba963b4d990cf97ad95487c8bf6 Mon Sep 17 00:00:00 2001 From: zhiyu1998 Date: Tue, 21 Feb 2023 02:16:49 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=88=20perf:=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E5=B0=8F=E8=93=9D=E9=B8=9F=E8=A7=A3=E6=9E=90=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/tools.js | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/apps/tools.js b/apps/tools.js index 3b213ed..6066a85 100644 --- a/apps/tools.js +++ b/apps/tools.js @@ -376,20 +376,21 @@ export class tools extends plugin { if (!fs.existsSync(downloadPath)) { mkdirsSync(downloadPath); } - // 开始读取数据 - if (resp.includes.media[0].type === "photo") { - // 图片 - resp.includes.media.map(item => { + // 逐个遍历判断 + for (let item of resp.includes.media) { + if (item.type === "photo") { + // 图片 const filePath = `${downloadPath}/${item.url.split("/").pop()}`; - this.downloadImgs(item.url, downloadPath).then(tmp => { + this.downloadImg(item.url, downloadPath).then(_ => { e.reply(segment.image(fs.readFileSync(filePath))); + fs.unlinkSync(filePath) }); - }); - } else { - // 视频 - this.downloadVideo(resp.includes.media[0].variants[0].url, true).then(video => { - e.reply(segment.video(`${downloadPath}/temp.mp4`)); - }); + } else if (item.type === "video") { + // 视频 + this.downloadVideo(resp.includes.media[0].variants[0].url, true).then(_ => { + e.reply(segment.video(`${downloadPath}/temp.mp4`)); + }); + } } }); return true; @@ -607,7 +608,7 @@ export class tools extends plugin { } // 工具:下载一张网络图片 - async downloadImgs(img, dir) { + async downloadImg (img, dir) { const filename = img.split("/").pop(); const filepath = `${dir}/${filename}`; const writer = fs.createWriteStream(filepath); @@ -628,8 +629,16 @@ export class tools extends plugin { .then(res => { res.data.pipe(writer); return new Promise((resolve, reject) => { - writer.on("finish", () => resolve(filepath)); - writer.on("error", reject); + writer.on("finish", () => { + writer.close(() => { + resolve(filepath); + }); + }); + writer.on("error", (err) => { + fs.unlink(filepath, () => { + reject(err); + }); + }); }); }); }