使用 fetch.pipe() 从discord.js 下载图像附件时出现问题

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

我有一个不和谐的机器人,我正在尝试从斜杠命令下载附件,但出现此错误:

TypeError: res.body.pipe is not a function

我尝试了这两行,但在管道上出现了相同的错误:

fetch(interaction.options.getAttachment('attachment').url)
    .then(res =>  {
        const dest = fs.createWriteStream(destination);
        res.body.pipe(dest);
    });

fetch(interaction.options.getAttachment('attachment').url).pipe(fs.createWriteStream(destination));
javascript node.js discord.js fetch
1个回答
0
投票

您收到的错误消息,TypeError: res.body.pipe is not a function,通常在响应正文不采用预期的可读流格式时出现。

在 Node.js 中处理获取请求时,响应可能并不总是提供可以通过管道传输到可写流中的直接主体属性。要处理从 URL 下载文件,您应该调整处理响应数据的方式。

您可以尝试以下方法:

const fetch = require('node-fetch');
const fs = require('fs');

// Assuming interaction.options.getAttachment('attachment').url retrieves the attachment URL
const attachmentURL = interaction.options.getAttachment('attachment').url;
const destination = 'path/to/save/your/file.extension'; // Provide the destination path

fetch(attachmentURL)
    .then(res => {
        const dest = fs.createWriteStream(destination);

        // Instead of directly piping, you can manually write the response to the writable stream
        res.body.on('data', chunk => {
            dest.write(chunk);
        });

        res.body.on('end', () => {
            dest.end();
            console.log('File downloaded successfully.');
        });
    })
    .catch(err => {
        console.error('Error downloading the file:', err);
    });

此方法通过监听数据事件并将每个数据块写入可写流来手动处理响应(

dest
)。一旦收到整个响应(
end
事件),它就会结束可写流。

请记住将

path/to/save/your/file.extension
替换为您要保存下载文件的目标位置,并确保对
fetch
操作进行正确的错误处理。

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