ky-universal

Use Ky in both Node.js and browsers

Github星跟蹤圖

ky-universal Build Status

Use Ky in both Node.js and browsers

Ky is made for browsers, but this package makes it possible to use it in Node.js too, by polyfilling most of the required browser APIs using node-fetch and abort-controller.

This package can be useful for:

  • Isomorphic code
  • Web apps (React, Vue.js, etc.) that use server-side rendering (SSR)
  • Testing browser libraries using a Node.js test runner

Note: Before opening an issue, make sure it's an issue with Ky and not its polyfills. Generally, if something works in the browser, but not in Node.js, it's an issue with node-fetch or abort-controller.

Keep in mind that Ky targets modern browsers when used in the browser. For older browsers, you will need to transpile and use a fetch polyfill.

If you only target Node.js, I would strongly recommend using Got instead.

Install

$ npm install ky ky-universal

Note that you also need to install ky.

Usage

const ky = require('ky-universal');

(async () => {
	const parsed = await ky('https://httpbin.org/json').json();

	// …
})();

ReadableStream support

For ReadableStream support, also install web-streams-polyfill:

$ npm install web-streams-polyfill

You can then use it normally:

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.

FAQ

How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?

Use it like you would use Ky:

import ky from 'ky-universal';

(async () => {
	const parsed = await ky('https://httpbin.org/json').json();

	// …
})();

Webpack will ensure the polyfills are only included and used when the app is rendered on the server-side.

How do I test a browser library that uses Ky in AVA?

Put the following in package.json:

{
	"ava": {
		"require": [
			"ky-universal"
		]
	}
}

The library that uses Ky will now just work in AVA tests.

  • ky - Tiny and elegant HTTP client based on the browser Fetch API
  • got - Simplified HTTP requests in Node.js

主要指標

概覽
名稱與所有者sindresorhus/ky-universal
主編程語言JavaScript
編程語言JavaScript (語言數: 2)
平台
許可證MIT License
所有者活动
創建於2019-02-22 16:39:06
推送於2023-09-01 21:26:23
最后一次提交
發布數18
最新版本名稱v0.12.0 (發布於 2023-07-28 20:54:05)
第一版名稱v0.1.0 (發布於 2019-02-22 23:48:26)
用户参与
星數673
關注者數5
派生數20
提交數46
已啟用問題?
問題數38
打開的問題數2
拉請求數8
打開的拉請求數0
關閉的拉請求數2
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?