使用fetch.pipe()从discord.js下载附件时遇TypeError错误
解决Discord机器人斜杠命令下载附件时的pipe报错问题
错误详情
你碰到的错误:
TypeError: res.body.pipe is not a function
你尝试的两种写法均触发该错误:
写法1:
fetch(interaction.options.getAttachment('attachment').url) .then(res => { const dest = fs.createWriteStream(destination); res.body.pipe(dest); });
写法2:
fetch(interaction.options.getAttachment('attachment').url).pipe(fs.createWriteStream(destination));
错误原因
你使用的fetch API(不管是浏览器环境还是Node.js 18+的原生fetch)返回的res.body是Web API标准的ReadableStream,而Node.js的文件流fs.createWriteStream()需要和Node.js内置的Stream对象配合,Web Stream并没有pipe()方法,所以直接调用会报错。
解决方案
方案1:使用node-fetch v2版本
node-fetch的v2版本返回的res.body是Node.js Stream,天然支持pipe()。
首先安装指定版本:
npm install node-fetch@2
修改代码:
const fetch = require('node-fetch'); fetch(interaction.options.getAttachment('attachment').url) .then(res => { const dest = fs.createWriteStream(destination); res.body.pipe(dest); });
方案2:转换Web Stream为Node.js Stream(Node 18+适用)
Node.js 18及以上版本提供了stream.webToNodeStream()方法,可以把Web Stream转换成Node.js Stream:
const fs = require('fs'); const { webToNodeStream } = require('stream/web'); fetch(interaction.options.getAttachment('attachment').url) .then(res => { const nodeStream = webToNodeStream(res.body); const dest = fs.createWriteStream(destination); nodeStream.pipe(dest); });
方案3:改用axios库
axios支持直接返回Node.js Stream,配置responseType: 'stream'即可:
首先安装axios:
npm install axios
修改代码:
const axios = require('axios'); const fs = require('fs'); axios({ url: interaction.options.getAttachment('attachment').url, method: 'GET', responseType: 'stream' }).then(res => { res.data.pipe(fs.createWriteStream(destination)); });
内容的提问来源于stack exchange,提问作者Rako Games
相关产品推荐
相关产品推荐

