More Related Content Similar to Andrii Shumada ''Use cases of Node.js Streams'' (20) More from OdessaJS Conf (20) Andrii Shumada ''Use cases of Node.js Streams''1. Use cases of Node.js
Streams
Andrii Shumada
Sr. Dev at Debitoor/Ciklum
Tw: @eagleeye_s
Gh: @eagleeye
2. About me
7 years in commercial development
5 years in JS
Judge at DEV_CHALLENGE
Program expert at js fwdays
Own projects:
Tank.ly
hvz.kiev.ua
2
4. Content < 1.4 GB
Node.js service for sharing porn files
Read file in
variable
Send to http
response
8. Event: 'data'
Event: 'end'
Event: 'error'
readable.read([size])
readable.pipe()
Class: stream.Readable
Data source
Data
chunks
https://nodejs.org/dist/latest-v6.x/docs/api/stream.html
11. Readable streams: 2) Databases
http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#stream
12. Readable streams: 2) Database cursors
http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#stream
19. Send data without streams
Read data
Transform data
time
Send dataMemory
consumption
20. Send data with streams
time
Read data
Transform data
Send data
Memory
consumption
22. Send file between browsers without storing
First browser
sends data
Proxy backend
Second browser
reads data
Memory
consumption
time
27. Multifetch endpoints
Suppose you have an API
- GET api/users, api/users/:id
- GET api/customers, api/customers:id
- GET api/countries etc
GET api/fetch?users=api/users&customer=api/customers/23&countries=api/countries
should return {“users”: [..], “customer”: {..}, “countries”: [..] }
30. {“users”: [..], “customer”: {..}, “countries”: [..] }
{
“users”
:
json1
,
“products”
:
json2
,
…
}
write(‘{“users”:’);
request(‘/api/users’).pipe(res)
write(‘,“products”:’);
request(‘/api/customer).pipe(res)
res.end(‘}’);
35. Conclusion:
- Streams save your memory
- Streams speed up data transfer
- Streams are not blocking your main thread
- Use streams every time you are working with data