Last active
December 20, 2015 16:18
-
-
Save spion/6160009 to your computer and use it in GitHub Desktop.
Read streams using jmar777's suspend
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 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(); |
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
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! |
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 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this could be done in parallel:
https://gist.github.com/spion/6160009#file-suspend-select-js-L35-L38