Last active
June 22, 2019 19:15
-
-
Save johnbender/9d4642ab6e6c3cf1f912f7892f6d403c to your computer and use it in GitHub Desktop.
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
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