From c73efcad7ea338064cda49ec793f01fdf9ac1135 Mon Sep 17 00:00:00 2001 From: Richie Bendall Date: Fri, 14 Feb 2020 20:37:28 +1300 Subject: [PATCH] Add optional `ReadableStream` polyfill (#12) Co-authored-by: Sindre Sorhus --- index.js | 6 ++++++ package.json | 8 +++++++- readme.md | 22 ++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 84a47a9..cb6099a 100644 --- a/index.js +++ b/index.js @@ -22,4 +22,10 @@ if (!global.AbortController) { global.AbortController = AbortController; } +if (!global.ReadableStream) { + try { + global.ReadableStream = require('web-streams-polyfill/ponyfill/es2018'); + } catch (_) {} +} + module.exports = require('ky/umd'); diff --git a/package.json b/package.json index 94eb65f..49f8355 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,13 @@ "xo": "^0.25.3" }, "peerDependencies": { - "ky": ">=0.17.0" + "ky": ">=0.17.0", + "web-streams-polyfill": ">=2.0.0" + }, + "peerDependenciesMeta": { + "web-streams-polyfill": { + "optional": true + } }, "browser": "browser.js", "ava": { diff --git a/readme.md b/readme.md index a8d9742..860d50e 100644 --- a/readme.md +++ b/readme.md @@ -35,6 +35,28 @@ const ky = require('ky-universal'); })(); ``` +## `ReadableStream` support + +For [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) support, also install [`web-streams-polyfill`](https://github.com/MattiasBuelens/web-streams-polyfill): + +``` +$ npm install web-streams-polyfill +``` + +You can then use it normally: + +```js +const ky = require('ky-universal'); + +(async () => { + const {body} = await ky('https://httpbin.org/bytes/16'); + const {value} = await body.getReader().read(); + const result = new TextDecoder('utf-8').decode(value); + + // … +})(); +``` + ## API The API is exactly the same as the [Ky API](https://github.com/sindresorhus/ky#api).