Created
May 27, 2014 16:33
-
-
Save Kuirak/826895c13d65da37eb29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var stream = require('stream') | |
,util =require('util'); | |
util.inherits(ConstantStream,stream.Readable); | |
function ConstantStream(constant){ | |
stream.Readable.call(this,{objectMode:true}); | |
this.constant =constant; //get count form Cache | |
} | |
ConstantStream.prototype._read = function(){ | |
var value ={}; | |
value.name ='constant'; | |
value.data =this.constant; | |
this.push([value]); | |
}; | |
//simple Console write stream | |
util.inherits(ConsoleStream,stream.Writable); | |
function ConsoleStream(){ | |
stream.Writable.call(this,{objectMode:true}); | |
} | |
ConsoleStream.prototype._write = function(chunk,enc,next){ | |
console.log(chunk); | |
next(); | |
}; | |
var consoleStream = new ConsoleStream(); | |
//Concats array content | |
util.inherits(ConcatProcessor,stream.Transform); | |
function ConcatProcessor(){ | |
stream.Transform.call(this,{objectMode:true}); | |
} | |
ConcatProcessor.prototype._transform = function(chunk,enc,next){ | |
var result =''; | |
chunk.forEach(function(item){ | |
result +='-'+ item[0].data; | |
}); | |
this.push(result); | |
next(); | |
}; | |
var concatProcessor = new ConcatProcessor(); | |
//Combines multiple streams like a Multiplexer | |
function CombineStreams(){ | |
var data=[]; | |
var sources = Array.prototype.slice.call(arguments); | |
this.pipe =function(target){ | |
sources.forEach(function(stream){ | |
//TODO check if readable stream | |
stream.on('data',function(chunk){ | |
stream.pause(); | |
data.push(chunk); | |
if(data.length ===sources.length){ | |
target.write(data); | |
data =[]; | |
sources.forEach(function(stream){ | |
stream.resume(); | |
}) | |
} | |
}) | |
}); | |
return target; | |
} | |
} | |
var constant= new ConstantStream(3); | |
var constant2= new ConstantStream(2); | |
var constant3= new ConstantStream(1); | |
var test =new CombineStreams(constant,constant2,constant3).pipe(concatProcessor); | |
test.pipe(consoleStream); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment