Skip to content

Instantly share code, notes, and snippets.

@johnbender
Last active June 22, 2019 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbender/9d4642ab6e6c3cf1f912f7892f6d403c to your computer and use it in GitHub Desktop.
Save johnbender/9d4642ab6e6c3cf1f912f7892f6d403c to your computer and use it in GitHub Desktop.
class AsyncLineStream {
constructor(stream){
this._lines = [];
this._readline = require('readline').createInterface({
input: stream
});
this._updateReadLinePromise();
}
_updateReadLinePromise(){
this._readlinePromise = new Promise((resolve) => {
var closer;
this._readline.once('close', closer = () => {
this._readlinePromise = Promise.resolve();
resolve();
});
this._readline.once('line', (line) => {
this._lines.push(line);
this._readline.removeListener('close', closer);
this._updateReadLinePromise();
resolve();
})
})
}
[Symbol.asyncIterator](){
return {
// TODO doesn't pull lines when waiting for new lines
next: async () => {
await this._readlinePromise;
var line = this._lines.shift();
return { done: line === undefined , value: line };
}
};
}
};
(async () => {
var i = 0;
for await (let line of new AsyncLineStream(process.stdin)) { // iterates over the arr
console.log(line);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment