bufferednetworkrequest
v1.1.1
Published
Make your interfaces render ~30% faster on 3G using streams and partial JSON parsing.
Maintainers
Readme
BufferedNetworkRequest
Make your interfaces render ~30% faster on 3G using streams and partial JSON parsing.
- Stream network requests as they arrive
- Extract valid JSON objects from incomplete chunks
- ~30% faster First Contentful Paint on 3G
Installation
NPM
npm install bufferednetworkrequestCDN
Import the module directly:
import * as BufferedNetworkRequest from 'https://unpkg.com/bufferednetworkrequest'Usage
Streaming JSON objects
import { JSONObjectStream } from 'bufferednetworkrequest'
const response = await fetch('https://jsonplaceholder.typicode.com/photos')
if (!response.ok) throw new Error(`Request failed: Code ${response.status}`)
if (!response.body) throw new Error(`Response was empty.`)
const stream = new JSONObjectStream(response.body)
let respObjects = []
for await (const objects of stream) {
// do something with the chunk
respObject.push(...objects)
}
console.log(respObjects)Streaming Text
import { TextStream } from 'bufferednetworkrequest'
const response = await fetch(url)
if (!response.ok) throw new Error(`Request failed: Code ${response.status}`)
if (!response.body) throw new Error(`Response was empty.`)
const stream = new TextStream(response.body)
let text = ''
for await (const textChunk of stream) {
// do something with the chunk
text += textChunk
}
console.log(text)Architecture
The library uses the Web Streams API. TextStreamInterface<ChunkType> is an abstract base class that pipes a Response.body through a TextDecoderStream and exposes an async iterator. Subclasses implement processChunk() to transform each text chunk:
- TextStream — Returns raw text chunks as-is
- JSONObjectStream — Accumulates chunks into a JSON string, uses
IncompleteJSONParserto extract complete objects as they come in, and yields only newly-completed objects (no duplicates across iterations) - IncompleteJSONParser — Extracts valid JSON objects from incomplete chunks by tracking brace nesting to find the last fully-closed object, and closing unclosed top-level arrays
Developing
npm install
npm run buildThen:
npm run test