您收到的错误消息,
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
活动