Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
stream between nodejs and whatwg
Search
Jxck
August 08, 2016
Technology
5
2k
stream between nodejs and whatwg
Talk about Stream API difference between node.js and whatwg
at #tng11 2016/08/08
Jxck
August 08, 2016
Tweet
Share
More Decks by Jxck
See All by Jxck
IE Graduation (IE の功績を讃える)
jxck
22
16k
IE Graduation Certificate
jxck
6
6k
RFC 9111: HTTP Caching
jxck
1
660
tc39_study_2
jxck
1
7.4k
IETF における ABNF とプロトコルパーサの話 / ABNF for Protocol Parser @ IETF
jxck
2
1k
Web Components 元年 v3 / Web Components first year v3
jxck
1
1k
Periodic Background Sync
jxck
0
540
Podcast over PWA
jxck
0
240
Yearly Web 2019
jxck
0
160
Other Decks in Technology
See All in Technology
リアルタイム分析データベースで実現する SQLベースのオブザーバビリティ
mikimatsumoto
0
1.3k
なぜ私は自分が使わないサービスを作るのか? / Why would I create a service that I would not use?
aiandrox
0
710
組織貢献をするフリーランスエンジニアという生き方
n_takehata
1
1.3k
クラウドサービス事業者におけるOSS
tagomoris
0
250
Platform Engineeringは自由のめまい
nwiizo
4
2.1k
開発組織のための セキュアコーディング研修の始め方
flatt_security
3
2.1k
2024.02.19 W&B AIエージェントLT会 / AIエージェントが業務を代行するための計画と実行 / Algomatic 宮脇
smiyawaki0820
12
3k
Classmethod AI Talks(CATs) #17 司会進行スライド(2025.02.19) / classmethod-ai-talks-aka-cats_moderator-slides_vol17_2025-02-19
shinyaa31
0
110
飲食店予約台帳を支えるインタラクティブ UI 設計と実装
siropaca
7
1.7k
人はなぜISUCONに夢中になるのか
kakehashi
PRO
6
1.6k
リーダブルテストコード 〜メンテナンスしやすい テストコードを作成する方法を考える〜 #DevSumi #DevSumiB / Readable test code
nihonbuson
11
7.1k
レビューを増やしつつ 高評価維持するテクニック
tsuzuki817
1
680
Featured
See All Featured
Adopting Sorbet at Scale
ufuk
74
9.2k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
7
630
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
47
5.2k
Done Done
chrislema
182
16k
Building Flexible Design Systems
yeseniaperezcruz
328
38k
Raft: Consensus for Rubyists
vanstee
137
6.8k
Navigating Team Friction
lara
183
15k
Designing for humans not robots
tammielis
250
25k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
330
21k
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
The Power of CSS Pseudo Elements
geoffreycrofte
75
5.5k
Making the Leap to Tech Lead
cromwellryan
133
9.1k
Transcript
Stream b/w node.js & whatwg Tokyo Node Gakuen #tng22 2016/8/8
Jxck
• id: Jxck • github: Jxck • twitter: @jxck_ •
blog: https://blog.jxck.io • podcast: http://mozaic.fm • Love: music Jack
mozaic.fm ep10 Node.js 3 https://mozaic.fm/episodes/10/nodejs.html
4 Node.js の Stream API で「データの流れ」を扱う方法 - Block Rockin’ Codes
“Stream を制す者は Node を制す” 5
“Stream を制す者は Node を制す” 6 から 5 年...
7 WHATWG Streams Stream API がブラウザにやってくる - Block Rockin’ Codes
先に結論 8 互換性など無い
Stream とは?(哲学) 9
Common Terminology 10
11 概念としての Stream File Process Network File Process Network Without
Stream(データをまとめて次に渡す) With Stream(データを得られた順に次に渡す) then(buffer) pipe(chunk) then(buffer) pipe(chunk)
12 両者の供述を聞く
• 非同期は Callback が基本 • 引数にルールを決めて扱いやすくしよう • 連続するイベントは EventEmitter •
EventEmitte の上位 API が Stream • Multi-Consumer • カスタマイズは継承 13 In Node.js Stream data data data data data data data data data data data data
14 In WHATWG • 非同期は Promise を返してこう • Async/Await でそれを便利にしよう
• もちろん Stream は Promise のジェネレータ • (≠ ES6 Generator) • Single-Consumer • カスタマイズはコンストラクタ Stream Promise
diff of Basic Async Handling 15 // Node.js - Callback
file.readFile(path, (error, data) => { console.log(error, data); }); // WHATWG(@2016) - Promise cache.match(req).then((res) => { console.log(res); }).catch((error) => { console.error(errror); });
node.js stream // ReadableStream extends Stream (extends EventEmitter) readableStream.on(‘data’, (value)
=> { console.log(value); }); readableStream.on(‘end’, () => { console.log(‘done’); }); readableStream.on(‘error’, (error) => { console.error(error); }); 16
whatwg stream let reader = readableStream.getReader(); // read() を呼ぶと chunk
を resolve する promise が返る reader.read().then(function processResult({done, value}) { if (done) return; console.log(value); // read() の呼び出しを再帰する return reader.read().then(processResult); }).catch((error) => { console.error(error); }); 17
node.js pipe readable .pipe(transform) // return readable .pipe(transform) // return
readable .pipe(writable) // return readable .on('end') .on('error'); 18
whatwg pipe readable .pipeThrough(transform1) // return readable .pipeThrough(transform2) // return
readable .pipeTo(writable) // return promise .then(done) .catch(fail); 19
whatwg tee() const [r1, r2] = readableStream.tee(); Promise.all([ r1.pipeTo(cache), //
データは同一参照 r2.pipeTo(upload) ]) .then(() => console.log('done')) .catch((err) => console.error(err)); 20
Push/Pull Source/Sync • Source ◦ underlying source ◦ データの生成元 •
Sink ◦ underlying sink ◦ データの渡す先 • Push Underlying Source ◦ 勝手に湧き出てくる ◦ TCP, Click, Timer etc • Pull Underlying Source ◦ 欲しい時に取り出す ◦ File, Random etc 21
backpressure • read の生成が write の消費より早い場合 ◦ そのままだと write が間に合わず溢れる
◦ write の buffer を見て read を止める方法 • いつ backpressure をかけるか ◦ queuing strategy で決める 22 File Process Network 速 遅 ちょっと待って!
queuing stragtegy • backpressure の戦略 ◦ 内部の queue の管理戦略 ◦
high-water mark を決める ◦ queue の空き < hwm だったら backpressure • 組み込み queuing strategy ◦ count queuing strategy (HWM == count) ◦ bytelength queuing strategy (HWM == size) 23 速 遅 二つ空くまでは ストップで HWM
独自 Stream socketStream = new ReadableStream({ start(controller) { socket.on('data', (e)
=> controller.enqueue(e.data)); socket.on('end', () => controller.close()); socket.on('error', (err) => controller.error(err)); }, cancel() { socket.close(); } }); 24
backpressure 付き readable socketStream = new ReadableStream({ start(controller) { socket.on('data',
(e) => { if (controller.desiredSize <= 0) { socket.readStop(); // backpressure } controller.enqueue(e.data); }); }, pull() { // resume socket.readStart(); }); 25
backpressure 付き writable fileStream = new WritableStream({ start() { return
fs.open(filename, "w").then(result => { this.fd = result; }); }, write(chunk) { // promise を返す return fs.write(this.fd, chunk, 0, chunk.length); } close() { return fs.close(this.fd); } }); 26
Observable ? 27 • Stream ◦ WHATWG Spec ◦ あくまで
I/O の抽象化 ◦ 伝達対象はデータの Chunk ◦ backpressure のサポート ◦ tee() を覗き、基本 single-comsumer • Observable ◦ ECMAScript Spec ◦ 連続イベントの抽象化 ◦ イベントそのものだから間引くなどの発想がある ◦ backpressure 無し ◦ multi-consumer 前提 How do readable streams relate to observables or EventTarget?
まとめ 28 • node - whatwg 間で Stream に互換はない ◦
非同期の表現(promise) から来る差 ◦ stream は promise のジェネレータ ◦ 変換するなら node2whawg の方が楽そう • 似てるけど違う用途 ◦ whatwg stream は I/O のため ◦ observable は event のため • お気持ち ◦ i8c なんてなかった
Fin 29
Jack