Skip to content

Instantly share code, notes, and snippets.

@spion
Last active December 20, 2015 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spion/6160009 to your computer and use it in GitHub Desktop.
Save spion/6160009 to your computer and use it in GitHub Desktop.
Read streams using jmar777's suspend
var suspend = require('suspend');
var http = require('http');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
function selector(streams) {
var queue = new EventEmitter();
queue.items = [];
streams.forEach(function(s) {
function emit(err) {
queue.items.push([err, s]);
queue.emit('data');
}
s.on('readable', emit);
s.on('error', emit);
});
return function select(cb) {
function drain() {
if (queue.items.length) {
err_stream = queue.items.shift();
cb(err_stream[0], err_stream[1]);
}
else
queue.once('data', drain);
}
drain();
};
}
function nothing(t, cb) {
setTimeout(function() { cb(null, 'empty'); }, t);
};
var main = suspend(function* (resume) {
var c1 = yield http.get('http://gist.github.com/isaacs/6143332',
resume.raw())
var c2 = yield http.get('http://gist.github.com/isaacs/6093040',
resume.raw());
var s1 = c1[0], s2 = c2[0];
var select = selector([s1, s2]);
while (ready = yield select(resume)) {
var which = ready == s1 ? 's1'
: ready == s2 ? 's2' : '??';
var data = ready.read();
console.log(which, data && data.length);
console.log(yield nothing(100, resume));
if (!s1.readable && !s2.readable) break;
}
console.log("All done!");
})
main();
13752 % nvm use 0.11.3 && node --harmony-generators example-select.js
Now using node v0.11.3
s1 13757
empty
s2 13248
empty
s2 8464
empty
s2 9172
empty
All done!
var suspend = require('suspend');
var main = suspend(function* (resume) {
var stream = process.stdin, data;
while (data = yield stream.once('data', resume.raw())) {
console.log(data[0].toString());
}
})
main();
@dominictarr
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment