Skip to content

Instantly share code, notes, and snippets.

@spion spion/suspend-select.js
Last active Dec 20, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

dominictarr commented Aug 6, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.