Withoutstreaming
Process Render
Fetch
Process Render
Fetch
Withstreaming
https://jakearchibald.com/2016/streams-ftw/
3
Slide 4
Slide 4 text
Node.JS Stream
A stream is an abstract interface for working with streaming data in Node.js.
Streams can be readable, writable, or both. All streams are instances of
EventEmitter.
Buffer: handle pieces of data
I/O data: consume less memory, save more resources
Gulp uses streams
”
4
ReactDOMServer.renderToNodeStream
pipe(res)
React 16 Server Side Rendering
app.get('/', (req, res) => {
(
). ;
});
7
Slide 8
Slide 8 text
8
Web Streams
Slide 9
Slide 9 text
Web Streams
This specification provides APIs for creating, composing, and consuming
streams of data that map efficiently to low-level I/O primitives.
only two types of streams , readable and writable streams
https://streams.spec.whatwg.org/
”
9
Slide 10
Slide 10 text
start
pull
cancel
ReadableStream
const readableStream = new ReadableStream({
(controller) {},
(controller) {},// called when stream's buffer isn't full
(reason) {}
}, queuingStrategy);
console.log(readableStream.constructor.prototype);
10
Slide 11
Slide 11 text
ReadableStreamDefaultController
• controller.enqueue(chunk) // queue data in buffer
• controller.close()
• controller.error(e)
• controller.desiredSize // the amount of buffer remaining
https://jsbin.com/fahavoz/edit?js,console
11
queueingStrategy
• CountQueueingStrategy
• ByteLengthQueueingStrategy
new CountQueuingStrategy({ highWaterMark: 1 })
default used is a CountQueuingStrategy with a high water mark of 1
19
backpressure
Flow control
• desiredSize
• can be negative, if the queue is over-full
• writer.ready
• Returns a Promise that resolves when the desired size of the stream's
internal queue transitions from non-positive to positive, signaling that it
is no longer applying backpressure.
22
Cancelling
A stream can be cancelled using stream.cancel()
• response.body.cancel()
• reader.cancel()
https://jsbin.com/gameboy/edit?js,console
25
Slide 26
Slide 26 text
'fetch'
respondWith
Service Worker
self.addEventListener( , event => {
event. (new Response(stream, {
headers: {'Content-Type': 'text/html'}
}));})
https://glitch.com/edit/#!/html-sw-stream?path=public/sw.js:1:0
https://jakearchibald.github.io/isserviceworkerready/demos/simple-stream/
26
Slide 27
Slide 27 text
async
for await chunk of response.body
Async iterators
function getResponseSize(url) {
const response = await fetch(url);
let total = 0;
(const ) {
total += chunk.length;
}
return total;}
27
Recap
• Streams handle sources of data in a memory efficient way
• Web Streams is available with Fetch API
• Handle Web Stream in Service Worker
• Better performance for Progressive Web App
31
Slide 32
Slide 32 text
Thanks!
@kidwm
Ref:
• 2016 - the year of web streams by Jake Archibald
• A Guide to Faster Web App I/O and Data Operations with Streams by Umar
Hansa
32