Skip to content

Instantly share code, notes, and snippets.

@Olegas
Last active August 29, 2015 14:16
Show Gist options
  • Save Olegas/7a04d5a58bd931827eb1 to your computer and use it in GitHub Desktop.
Save Olegas/7a04d5a58bd931827eb1 to your computer and use it in GitHub Desktop.
Read file stream line by line using generators
// You need some block element with id = 'log' to see output
asyncWrap(function *() {
var currentTime;
log('Lets wait 5 sec');
currentTime = yield promiseFromTimer(5000);
log('Current time is ' + currentTime + '. Now lets wait 10 sec');
try {
currentTime = yield exceptionFromTimer(10000);
// Will never happen
log('Current time is ' + currentTime + '. Ok then, lets stop');
} catch(e) {
log('Got exception: ' + e + ' at ' + (new Date()));
}
var fourtytwo = yield plusTwo(40);
log('And... the meaning of life is ' + fourtytwo);
});
function asyncWrap(g) {
function step(v) {
var val = (v instanceof Error ? it.throw(v) : it.next(v));
if (val.done) {
return;
}
val = val.value;
if (val instanceof Promise) {
val.then(step, step);
} else {
step(val);
}
}
var it = g();
step();
}
function plusTwo(n) {
return n + 2;
}
function promiseFromTimer(delay) {
return new Promise(function(fulfil) {
setTimeout(fulfil.bind(null, new Date()) , delay);
});
}
function exceptionFromTimer(delay) {
return new Promise(function(fulfil, reject) {
setTimeout(reject.bind(null, new Error('Oh!')), delay);
});
}
function log(s) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(s));
document.getElementById('log').appendChild(p);
}
function readStreamByLine(stream, handler) {
var res = '', completed = false;
stream.pause();
stream.on('data', function(chunk) {
// Assume we have only ascii data, no UTF
res += chunk.toString();
check();
});
stream.on('end', function() {
completed = true;
check();
});
function check() {
var
nlIdx = res.indexOf('\n'),
line;
if (nlIdx !== -1) {
line = res.substr(0, nlIdx);
res = res.substr(nlIdx + 1);
stream.pause();
it.next(line);
} else {
if (completed) {
res && it.next(res);
it.next(false);
} else {
stream.resume();
}
}
}
var it = handler(function() {
setImmediate(check);
});
it.next();
}
var strm = require('fs').createReadStream(__filename);
readStreamByLine(strm, function *gen(nextPlease) {
while(true) {
var line = yield nextPlease();
if (line === false) {
return;
}
console.log('Got line: ' + line);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment