Created
May 24, 2012 18:43
-
-
Save kevinswiber/2783399 to your computer and use it in GitHub Desktop.
Readable/Writable Stream in Node.js
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
var Stream = require('stream'); | |
var util = require('util'); | |
var Streamy = function() { | |
Stream.call(this); | |
this.readable = true; | |
this.writable = true; | |
}; | |
util.inherits(Streamy, Stream); | |
Streamy.prototype.write = function(string) { | |
console.log('writing to self:', string); | |
if (this.listeners('data').length) { | |
console.log('sending data to reader:', string); | |
this.emit('data', string); | |
} | |
}; | |
process.stdin.setEncoding('utf8'); | |
process.stdin.resume(); | |
var stream1 = new Streamy(); | |
var stream2 = new Streamy(); | |
process.stdin.pipe(stream1).pipe(stream2); | |
/* | |
λ node streamy.js | |
Hello, streams! | |
writing to self: Hello, streams! | |
sending data to reader: Hello, streams! | |
writing to self: Hello, streams! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thx, mate. Finally found great example!