代码之家  ›  专栏  ›  技术社区  ›  Rako Games

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

  •  0
  • Rako Games  · 技术社区  · 2 年前

    我有一个discord bot,我正试图从斜杠命令下载附件,但我收到了以下错误:

    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));
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   collab-with-tushar-raj    2 年前

    您收到的错误消息, TypeError:res.body.pipe不是函数 ,通常在响应主体不是预期的可读流格式时出现。

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

    以下是您可以尝试的方法:

    const fetch = require('node-fetch');
    const fs = require('fs');
    const stream = require('stream');
    
    // 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 => {
            if (!res.ok) {
                throw new Error(`Failed to download file: ${res.status} ${res.statusText}`);
            }
    
            const dest = fs.createWriteStream(destination);
    
            // Use pipeline to handle streams
            stream.pipeline(res.body, dest, err => {
                if (err) {
                    console.error('Pipeline failed:', err);
                } else {
                    console.log('File downloaded successfully.');
                }
            });
        })
        .catch(err => {
            console.error('Error downloading the file:', err);
        });
    

    此代码使用 stream.pipeline 处理可读流的方法 res.body 并将其直接管道传输到可写流( dest ).它还包括获取操作和管道进程的错误处理。

    记得更换 path/to/save/your/file.extension 使用要保存下载文件的目的地,并确保正确处理 fetch 活动