由于某种原因,我在 TypeScript 中收到错误““ReadableStream”类型上不存在属性“pipe””。
代码:
fetch("https://raw.githubusercontent.com/Fizzify/dotfiles/main/wallpaper.jpg")
.then(
(res: Response) =>
new Promise((resolve, reject) => {
const dest = fs.createWriteStream("./Doom.png");
res.body!.pipe(dest);
res.body!.on("end", () => resolve("it worked"));
dest.on("error", reject);
})
)
.then(() => console.log("Done downloading!"));
我尝试使用其他管道方法,如pipeThrough或pipeTo,但没有任何乐趣。
我希望它能够下载图像并在下载的图像上使用管道。
我尝试使用 https 而不是 fetch,但也没有什么乐趣,因为它只下载了一个 0kb 的空图像。
res.body
是 JavaScript Streams API 定义的 ReadableStream(有时称为“Web 流”),而 fs.createWriteStream()
返回 Node.js Writable 流。这两种类型的流彼此不兼容,但它们可以相互转换。
考虑到 Streams API 是更新且更通用的标准,我的建议是在整个代码中使用它作为基础。您可以使用
Writable.toWeb()
将 Node.js Writable 流转换为 WritableStream。
ReadableStream 没有
pipe
方法,并且不会发出 end
事件,而是具有返回承诺的 pipeTo
方法。如果 ReadableStream 源或 WritableStream 目标因错误而中止,则 Promise 将自动被拒绝。
你的代码将像这样工作:
fetch("https://raw.githubusercontent.com/Fizzify/dotfiles/main/wallpaper.jpg")
.then(
(res: Response) =>
res.body.pipeTo(Writable.toWeb(fs.createWriteStream("./Doom.png")))
)
.then(() => console.log("Done downloading!"));