为什么fs.js返回[object Object]并关闭我的机器人程序?

问题描述 投票:0回答:1

我正在开发一款可以处理各种事情的不和谐机器人。它不断崩溃,我一直跟踪错误的根源。它的作用是下载以不和谐的私人消息发送给它的图像,对它们进行哈希处理并将其名称设置为哈希,以确保不存在重复项。这不是最有效的方法,但是可以。

这是我的代码(有点混乱)

message.attachments.forEach(url => {
    if (!message.author.bot) {
        function getDate() {
            let d = new Date().getTime();
            return d;
        }
        tempdate = new getDate();
        ext = path.extname(url.url);
        request.get(url).on(`error`, console.error).pipe(fs.createWriteStream(`./temp/Img-${tempdate}${ext}`));
        hash = sha256(`./temp/Img-${tempdate}${ext}`);
        if (fs.existsSync(`./attachments/Img-${hash}${ext}`)) {
            request.get(url).on(`error`, console.error).pipe(fs.createWriteStream(`./attachments/Img-${hash}${ext}`));
            console.log(`Error: Duplicate File`)
        }
        fs.createWriteStream(`./attachments/Img-${hash}${ext}`);
        console.log(`Wrote Hashed File.`)
        fs.unlinkSync(`./temp/Img-${tempdate}${ext}`)
    }
})

每隔一段时间,但是会返回此:

fs.js:1061
  return binding.unlink(pathModule._makeLong(path));
                 ^

Error: ENOENT: no such file or directory, unlink 'C:\Users\xxxxx\Desktop\testbot\temp\Img-[object Object].png'
    at Object.fs.unlinkSync (fs.js:1061:18)
    at Client.client.on.message (C:\Users\xxxxx\Desktop\testbot\yes.js:48:20)
    at emitOne (events.js:116:13)
    at Client.emit (events.js:211:7)
    at MessageCreateHandler.handle (C:\Users\xxxxx\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\xxxxx\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
    at WebSocketConnection.onPacket (C:\Users\xxxxx\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\xxxxx\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\xxxxx\node_modules\ws\lib\event-target.js:120:16)
    at emitOne (events.js:116:13)

我认为我在这里做错了。我在网上找不到任何答案

javascript node.js fs
1个回答
0
投票

您正在混合同步和异步代码。

.pipe()绝对是异步的,但是您试图假定它已立即完成。您不能以这种方式可靠地编程。

您需要先听一个事件来知道何时完成.pipe(),然后才能继续进行其他处理。

而且,一旦使它成为事件驱动的,您的.forEach()将先运行多个迭代,并尝试同时运行,然后您的变量未在循环内本地声明的事实将导致变量冲突。

此外,这行代码本身是做什么的:

fs.createWriteStream(`./attachments/Img-${hash}${ext}`);

您创建了一个写入流,但是甚至没有对其进行跟踪。那只会泄漏文件句柄。

© www.soinside.com 2019 - 2024. All rights reserved.