got 是 node.js 完成 HPPT request 的模块。
要对 API 完成一次请求非常简单:
const got = require("got");
got(url)
.then(response => console.log(response.body))
.catch(error => console.log(error.response.body));
下载文件可以使用 got.stream 方法,或设置 got 请求参数 isStream: true
got.stream(url);
// or
got(url, {
isStream: true });
got 的 stream 是“双工流”,可读可写。下载文件我们只需要可读。下载一个文件,我们需要以某种方式将响应发送到文件系统。流允许您通过管道将数据从一个流传输到另一个流使用。 使用 fs 模块的 createWriteStream 方法将流写入文件。
const got = require("got");
const {
createWriteStream } = require("fs");
const url =
"https://media0.giphy.com/media/4SS0kfzRqfBf2/giphy.gif";
got.stream(url).pipe(createWriteStream('image.gif'));
要处理进度和错误,我们先将获取流和写入流分开:
const got = require("got");
const {
createWriteStream } = require(<