Created
May 27, 2016 02:50
-
-
Save tangxinfa/b4c35057129cfdbf92dd9a88bbb67b90 to your computer and use it in GitHub Desktop.
Wrap readline's event based interface to co friendly
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 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; | |
}; |
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 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