SlideShare a Scribd company logo
1 of 26
Download to read offline
Learning a Node stream

            2012-01-28
     kumatch / Yosuke Kumakura
• Yosuke Kumakura (kumatch)
• @kumatch
•     Feedtailor inc.
• Video game fun
Agenda

• Summary
• Usage
• Case study
• Stream classes
Stream summary


• An abstract interface Node's I/O
• Controls data stream
• Readable / Writable stream
Case study


How to copy files on Node ?
var fs = require('fs');

var input = './oriainal.jpg';
var output = './copy.jpg';

var data = fs.readFileSync(input);
fs.writeFileSync(output, data);

console.log('copied.');
var fs = require('fs');

var input = './original.jpg';
var output = './copy.jpg';

fs.readFile(input, function (err, data) {
    if (err) throw err;

      fs.writeFile(output, data, function (err) {
         if (err) throw err;

            console.log('copied.');
      });
});
var fs = require('fs');
var readStream = fs.createReadStream('./original.jpg');
var writeStream = fs.createWriteStream('./copy.jpg');
readStream.resume();
readStream.on('data', function (buffer) {
    writeStream.write(buffer);
});
readStream.on('end', function () {
    writeStream.end();
});
writeStream.on('close', function () {
    console.log('copied');
});
var fs = require('fs');

var readStream = fs.createReadStream('./original.jpg');
var writeStream = fs.createWriteStream('./copy.jpg');

readStream.pipe(writeStream);

writeStream.on('close', function () {
    console.log('copied');
});
Stream usage


• Stream is EventEmmiter
• and has some methods.
Stream usage /
    Readable stream
• Methods
 • resume
 • pause
 • destroy
Stream usage /
    Readable stream
• Events
 • data
 • end
 • close
 • error
Stream usage /
    Writable stream
• Methods
 • write
 • end
 • destroy
Stream usage /
    Writable stream
• Events
 • drain
 • close
 • error
var fs = require('fs');
var readStream = fs.createReadStream('./original.jpg');
var writeStream = fs.createWriteStream('./copy.jpg');
readStream.resume();
readStream.on('data', function (buffer) {
    writeStream.write(buffer);
});
readStream.on('end', function () {
    writeStream.end();
});
writeStream.on('close', function () {
    console.log('copied');
});
Stream usage /
         Stream pipe()

                pipe
Source stream          Destination stream
  (readable)               (writable)
Stream usage /
        Stream pipe()

• destination.write() if source on ‘data’.
• source.pause() if destination buffer is full.
• source.resume() if destination on ‘drain’.
Stream usage /
        Stream pipe()

• [optional]
  Keeps the destination stream open.
   • Do not destination.end().
var fs = require('fs');

var readStream = fs.createReadStream('./original.jpg');
var writeStream = fs.createWriteStream('./copy.jpg');

readStream.pipe(writeStream);

writeStream.on('close', function () {
    console.log('copied');
});
Case study 2


Digest SHA1 hash of a file
Stream classes


• Filesystem (fs)
 • readStream (Readable)
 • writeStream (Writable)
Stream classes


• Net
 • net.Socket (Readable/Writable)
Stream classes


• HTTP
 • http.ServerRequest (Readable)
 • http.ServerResponse (Writable)
Stream classes

• Zlib
 • all classes (Readable/Writable)
   • Gzip/Gunzip
   • Deflate/Inflate
   • DeflateRaw/InflateRaw
Stream classes

fs.Readable


        pipe   zlib.Gzip


                     pipe   http.response
References
• Node manual & documentation
• by Jxck
 • http://d.hatena.ne.jp/Jxck/20111204
• A future in stream /
    Streams2 (Github issue)
 • https://github.com/joyent/node/pull/1681

More Related Content

What's hot

Rustでパケットと戯れる
Rustでパケットと戯れるRustでパケットと戯れる
Rustでパケットと戯れるShuyaMotouchi1
 
Gsummit apis-2012
Gsummit apis-2012Gsummit apis-2012
Gsummit apis-2012Gluster.org
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleHTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleKazuho Oku
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Codemotion
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB ShellMongoDB
 
Libral - a systems management API for Linux
Libral - a systems management API for LinuxLibral - a systems management API for Linux
Libral - a systems management API for Linuxlutter
 
Writing data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gemWriting data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gemSean S.G Wang
 
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp
 
The Popper Experimentation Protocol and CLI tool
The Popper Experimentation Protocol and CLI toolThe Popper Experimentation Protocol and CLI tool
The Popper Experimentation Protocol and CLI toolIvo Jimenez
 
In-core compression: how to shrink your database size in several times
In-core compression: how to shrink your database size in several timesIn-core compression: how to shrink your database size in several times
In-core compression: how to shrink your database size in several timesAleksander Alekseev
 
PHP Streams: Lucky Dip
PHP Streams: Lucky DipPHP Streams: Lucky Dip
PHP Streams: Lucky DipWez Furlong
 
Spark Gotchas and Lessons Learned
Spark Gotchas and Lessons LearnedSpark Gotchas and Lessons Learned
Spark Gotchas and Lessons LearnedJen Waller
 
Rethink db with Python
Rethink db with PythonRethink db with Python
Rethink db with PythonPrabhu Raghav
 
CRONtab Tutorial
CRONtab TutorialCRONtab Tutorial
CRONtab TutorialJoseph ...
 

What's hot (20)

Rustでパケットと戯れる
Rustでパケットと戯れるRustでパケットと戯れる
Rustでパケットと戯れる
 
Gsummit apis-2012
Gsummit apis-2012Gsummit apis-2012
Gsummit apis-2012
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleHTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB Shell
 
Libral - a systems management API for Linux
Libral - a systems management API for LinuxLibral - a systems management API for Linux
Libral - a systems management API for Linux
 
How do i Meet MongoDB
How do i Meet MongoDBHow do i Meet MongoDB
How do i Meet MongoDB
 
Comets notes
Comets notesComets notes
Comets notes
 
Reverse on go
Reverse on goReverse on go
Reverse on go
 
Writing data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gemWriting data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gem
 
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
 
The Popper Experimentation Protocol and CLI tool
The Popper Experimentation Protocol and CLI toolThe Popper Experimentation Protocol and CLI tool
The Popper Experimentation Protocol and CLI tool
 
Hypertable Nosql
Hypertable NosqlHypertable Nosql
Hypertable Nosql
 
In-core compression: how to shrink your database size in several times
In-core compression: how to shrink your database size in several timesIn-core compression: how to shrink your database size in several times
In-core compression: how to shrink your database size in several times
 
PHP Streams: Lucky Dip
PHP Streams: Lucky DipPHP Streams: Lucky Dip
PHP Streams: Lucky Dip
 
Spark Gotchas and Lessons Learned
Spark Gotchas and Lessons LearnedSpark Gotchas and Lessons Learned
Spark Gotchas and Lessons Learned
 
Linux cheat sheet
Linux cheat sheetLinux cheat sheet
Linux cheat sheet
 
Rethinkdb
RethinkdbRethinkdb
Rethinkdb
 
Rethink db with Python
Rethink db with PythonRethink db with Python
Rethink db with Python
 
CRONtab Tutorial
CRONtab TutorialCRONtab Tutorial
CRONtab Tutorial
 

Viewers also liked

Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & StreamsEyal Vardi
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IOEyal Vardi
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
OpenStreetMap in 3D using Python
OpenStreetMap in 3D using PythonOpenStreetMap in 3D using Python
OpenStreetMap in 3D using PythonMartin Christen
 
Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...
Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...
Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...Martin Christen
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...CA API Management
 
3d mit Python (PythonCamp)
3d mit Python (PythonCamp)3d mit Python (PythonCamp)
3d mit Python (PythonCamp)Martin Christen
 

Viewers also liked (11)

Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IO
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
OpenStreetMap in 3D using Python
OpenStreetMap in 3D using PythonOpenStreetMap in 3D using Python
OpenStreetMap in 3D using Python
 
Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...
Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...
Visualisation of Complex 3D City Models on Mobile Webbrowsers Using Cloud-bas...
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
 
GeoBeer July 3rd, 2013
GeoBeer July 3rd, 2013GeoBeer July 3rd, 2013
GeoBeer July 3rd, 2013
 
3d mit Python (PythonCamp)
3d mit Python (PythonCamp)3d mit Python (PythonCamp)
3d mit Python (PythonCamp)
 

Similar to Learning a node stream

C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptC-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptssuserad38541
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in CTushar B Kute
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
Functional Programming with Streams in node.js
Functional Programming with Streams in node.jsFunctional Programming with Streams in node.js
Functional Programming with Streams in node.jsAdam Crabtree
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with filesramya marichamy
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with fileskirupasuchi1996
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdfTigabu Yaya
 
FunctionalJS - May 2014 - Streams
FunctionalJS - May 2014 - StreamsFunctionalJS - May 2014 - Streams
FunctionalJS - May 2014 - Streamsdarach
 
File Handling in C Programming for Beginners
File Handling in C Programming for BeginnersFile Handling in C Programming for Beginners
File Handling in C Programming for BeginnersVSKAMCSPSGCT
 

Similar to Learning a node stream (20)

File handling in C
File handling in CFile handling in C
File handling in C
 
Java I/O
Java I/OJava I/O
Java I/O
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptC-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
 
File mangement
File mangementFile mangement
File mangement
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 
Data file handling
Data file handlingData file handling
Data file handling
 
Functional Programming with Streams in node.js
Functional Programming with Streams in node.jsFunctional Programming with Streams in node.js
Functional Programming with Streams in node.js
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
file
filefile
file
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
FunctionalJS - May 2014 - Streams
FunctionalJS - May 2014 - StreamsFunctionalJS - May 2014 - Streams
FunctionalJS - May 2014 - Streams
 
Ext 0523
Ext 0523Ext 0523
Ext 0523
 
File Handling in C Programming for Beginners
File Handling in C Programming for BeginnersFile Handling in C Programming for Beginners
File Handling in C Programming for Beginners
 

More from kumatch kumatch

AngularJSからReactに移ったケースの話
AngularJSからReactに移ったケースの話AngularJSからReactに移ったケースの話
AngularJSからReactに移ったケースの話kumatch kumatch
 
Node.js patterns of module export / require
Node.js patterns of module export / requireNode.js patterns of module export / require
Node.js patterns of module export / requirekumatch kumatch
 
Node.js Error & Debug Leveling
Node.js Error & Debug LevelingNode.js Error & Debug Leveling
Node.js Error & Debug Levelingkumatch kumatch
 
[Node] Multiprocessing and runs continuously
[Node] Multiprocessing and runs continuously[Node] Multiprocessing and runs continuously
[Node] Multiprocessing and runs continuouslykumatch kumatch
 
PHPカンファレンス関西2011/スマートフォン時代のWebシステム
PHPカンファレンス関西2011/スマートフォン時代のWebシステムPHPカンファレンス関西2011/スマートフォン時代のWebシステム
PHPカンファレンス関西2011/スマートフォン時代のWebシステムkumatch kumatch
 

More from kumatch kumatch (7)

AngularJSからReactに移ったケースの話
AngularJSからReactに移ったケースの話AngularJSからReactに移ったケースの話
AngularJSからReactに移ったケースの話
 
Node platforms
Node platformsNode platforms
Node platforms
 
Nodeを稼働させる
Nodeを稼働させるNodeを稼働させる
Nodeを稼働させる
 
Node.js patterns of module export / require
Node.js patterns of module export / requireNode.js patterns of module export / require
Node.js patterns of module export / require
 
Node.js Error & Debug Leveling
Node.js Error & Debug LevelingNode.js Error & Debug Leveling
Node.js Error & Debug Leveling
 
[Node] Multiprocessing and runs continuously
[Node] Multiprocessing and runs continuously[Node] Multiprocessing and runs continuously
[Node] Multiprocessing and runs continuously
 
PHPカンファレンス関西2011/スマートフォン時代のWebシステム
PHPカンファレンス関西2011/スマートフォン時代のWebシステムPHPカンファレンス関西2011/スマートフォン時代のWebシステム
PHPカンファレンス関西2011/スマートフォン時代のWebシステム
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Learning a node stream

  • 1. Learning a Node stream 2012-01-28 kumatch / Yosuke Kumakura
  • 2. • Yosuke Kumakura (kumatch) • @kumatch • Feedtailor inc. • Video game fun
  • 3. Agenda • Summary • Usage • Case study • Stream classes
  • 4. Stream summary • An abstract interface Node's I/O • Controls data stream • Readable / Writable stream
  • 5. Case study How to copy files on Node ?
  • 6. var fs = require('fs'); var input = './oriainal.jpg'; var output = './copy.jpg'; var data = fs.readFileSync(input); fs.writeFileSync(output, data); console.log('copied.');
  • 7. var fs = require('fs'); var input = './original.jpg'; var output = './copy.jpg'; fs.readFile(input, function (err, data) { if (err) throw err; fs.writeFile(output, data, function (err) { if (err) throw err; console.log('copied.'); }); });
  • 8. var fs = require('fs'); var readStream = fs.createReadStream('./original.jpg'); var writeStream = fs.createWriteStream('./copy.jpg'); readStream.resume(); readStream.on('data', function (buffer) { writeStream.write(buffer); }); readStream.on('end', function () { writeStream.end(); }); writeStream.on('close', function () { console.log('copied'); });
  • 9. var fs = require('fs'); var readStream = fs.createReadStream('./original.jpg'); var writeStream = fs.createWriteStream('./copy.jpg'); readStream.pipe(writeStream); writeStream.on('close', function () { console.log('copied'); });
  • 10. Stream usage • Stream is EventEmmiter • and has some methods.
  • 11. Stream usage / Readable stream • Methods • resume • pause • destroy
  • 12. Stream usage / Readable stream • Events • data • end • close • error
  • 13. Stream usage / Writable stream • Methods • write • end • destroy
  • 14. Stream usage / Writable stream • Events • drain • close • error
  • 15. var fs = require('fs'); var readStream = fs.createReadStream('./original.jpg'); var writeStream = fs.createWriteStream('./copy.jpg'); readStream.resume(); readStream.on('data', function (buffer) { writeStream.write(buffer); }); readStream.on('end', function () { writeStream.end(); }); writeStream.on('close', function () { console.log('copied'); });
  • 16. Stream usage / Stream pipe() pipe Source stream Destination stream (readable) (writable)
  • 17. Stream usage / Stream pipe() • destination.write() if source on ‘data’. • source.pause() if destination buffer is full. • source.resume() if destination on ‘drain’.
  • 18. Stream usage / Stream pipe() • [optional] Keeps the destination stream open. • Do not destination.end().
  • 19. var fs = require('fs'); var readStream = fs.createReadStream('./original.jpg'); var writeStream = fs.createWriteStream('./copy.jpg'); readStream.pipe(writeStream); writeStream.on('close', function () { console.log('copied'); });
  • 20. Case study 2 Digest SHA1 hash of a file
  • 21. Stream classes • Filesystem (fs) • readStream (Readable) • writeStream (Writable)
  • 22. Stream classes • Net • net.Socket (Readable/Writable)
  • 23. Stream classes • HTTP • http.ServerRequest (Readable) • http.ServerResponse (Writable)
  • 24. Stream classes • Zlib • all classes (Readable/Writable) • Gzip/Gunzip • Deflate/Inflate • DeflateRaw/InflateRaw
  • 25. Stream classes fs.Readable pipe zlib.Gzip pipe http.response
  • 26. References • Node manual & documentation • by Jxck • http://d.hatena.ne.jp/Jxck/20111204 • A future in stream / Streams2 (Github issue) • https://github.com/joyent/node/pull/1681