Skip to content

Instantly share code, notes, and snippets.

@tangxinfa
Created May 27, 2016 02:50
Show Gist options
  • Save tangxinfa/b4c35057129cfdbf92dd9a88bbb67b90 to your computer and use it in GitHub Desktop.
Save tangxinfa/b4c35057129cfdbf92dd9a88bbb67b90 to your computer and use it in GitHub Desktop.
Wrap readline's event based interface to co friendly
var co = require('co'),
assert = require('assert');
fs = require('fs'),
readline = require('readline');
module.exports = function (filename) {
var instance = {
lines: [],
closed: false,
errored: null,
callback: null,
read: function () {
return function (callback) {
assert(instance.callback === null);
if (instance.lines.length > 0) {
var line = instance.lines.shift()
callback(null, line);
if (instance.lines.length === 0) {
stream.resume();
}
return;
} else if (instance.closed) {
return callback(null, null);
} else if (instance.errored) {
return callback(instance.errored);
}
instance.callback = callback;
};
}
};
var stream = readline.createInterface({
input: fs.createReadStream(filename)
});
stream.on('line', function (line) {
instance.lines.push(line);
stream.pause();
if (instance.callback) {
var callback = instance.callback;
instance.callback = null;
callback(null, instance.lines.shift());
if (instance.lines.length == 0) {
stream.resume();
}
return;
}
}).on('close', function () {
instance.closed = true;
if (instance.callback && instance.lines.length == 0) {
var callback = instance.callback;
instance.callback = null;
return callback(null, null);
}
}).on('error', function (err) {
instance.errored = err;
if (instance.callback && instance.lines.length == 0) {
var callback = instance.callback;
instance.callback = null;
return callback(err);
}
});
return instance;
};
var co = require('co'),
readline = require('./co-readline');
co(function* () {
var hosts = readline('/etc/hosts');
while (true) {
var line = yield hosts.read();
if (typeof(line) == 'string') {
console.log('result line: ' + line);
continue;
}
break;
}
}).then(function (value) {
console.error("value: " + (value || '').toString());
}).catch(function (e) {
console.error("catch: " + e.stack);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment