Hugo Zapata
@hugozap
Mecanismo simple para conectar programas.
program1 | program2 | program3
UNIX Pipes
Su poder está en la facilidad con que se pueden encadenar pequeños programas para resolver problemas complejos.
Doug McIlroy, the inventor of Unix pipes
Intro a la filosofía Unix: http://www.catb.org/esr/writings/taoup/html/ch01s06.html
//Conectar stdin a stdout
process.stdin.pipe(process.stdout);
Básicos
Derivados de Transform (Ejemplos)
DataSource
paquete para crear/ manipular streams
npm install event-stream
Ej: Socket
Mux-Demux
var randomNumberStream = require('./randomNumberStream.js')
randomNumberStream.pipe(process.stdout);
Creando nuestros propios Streams
/**
* Retorna un stream que genera
* números aleatorios de manera infinita
*/
var Readable = require('readable-stream').Readable;
module.exports = function(){
var rs = new Readable({encoding:'utf8'});
/* Solo generamos un valor cuando estamos leyendo
del stream */
rs._read = function(){
var num = 1+Math.floor(Math.random()*100);
setTimeout(function(){
rs.push(num.toString(),'utf8');
},100);
}
return rs
};
Implementación básica Readable Stream
Ej "Fake Japonés"
var fakeJapanesse = require('./fakeJapanesseStream.js');
var es = require('event-stream');
var fs = require('fs');
process.stdin
.pipe(es.split(/[\r\s\n]/))
.pipe(fakeJapanesse)
.pipe(es.join(' '))
.pipe(process.stdout);
curl -sS http://norvig.com/big.txt | node translate
translate.js
/**
* Creación de un Stream (transform) básico
* usando through
*/
var through = require('through');
//------ Definición del nuevo stream -----//
var myStream = through(function write(bufferPalabra){
var opts = [
'iroki',
'aka',
'hari',
'tago',
'ichiwa',
'asai',
'anata',
'suka',
'maki'
]
this.push(bufferPalabra.toString() + opts[Math.floor(Math.random()*opts.length)]);
})
module.exports = myStream;
fakeJapanesseStream.js
Algunas herramientas útiles
Demo
https://github.com/substack/stream-handbook
https://github.com/sindresorhus/awesome-nodejs#streams
http://hugozap.com/development/2015/11/01/nodejs-streams-intro-diagrams/
http://hugozap.com/software/2014/12/21/shoe-mux-demux-example/
https://github.com/hugozap/bogotajs-fun-with-streams-workshop