From f574c2be5c986c4c66b32d51fd343987b0508055 Mon Sep 17 00:00:00 2001 From: Ivan Filenko Date: Wed, 21 Feb 2018 19:28:24 +0300 Subject: [PATCH 1/2] readline: add support for async iteration --- doc/api/readline.md | 57 ++++++ doc/api/stream.md | 3 + lib/_stream_readable.js | 2 +- lib/internal/readline/async_iterator.js | 166 ++++++++++++++++++ lib/internal/streams/async_iterator.js | 5 +- lib/readline.js | 33 +++- node.gyp | 1 + .../parallel/test-readline-async-iterators.js | 43 +++++ 8 files changed, 307 insertions(+), 3 deletions(-) create mode 100644 lib/internal/readline/async_iterator.js create mode 100644 test/parallel/test-readline-async-iterators.js diff --git a/doc/api/readline.md b/doc/api/readline.md index a2a4adf3093a9a..945c5ca35ef141 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -306,6 +306,37 @@ rl.write(null, { ctrl: true, name: 'u' }); The `rl.write()` method will write the data to the `readline` `Interface`'s `input` *as if it were provided by the user*. +### rl[@@asyncIterator] + + +> Stability: 1 - Experimental + +Returns an [AsyncIterator][async-iterator] to fully consume the stream. + +```js +const readline = require('readline'); +const fs = require('fs'); + +async function processLineByLine(readable) { + readable.setEncoding('utf8'); + const rli = readline.createInterface({ + input: readable, + crlfDelay: Infinity + }); + + for await (const line of rli) { + console.log(line); + } +} + +processLineByLine(fs.createReadStream('file')).catch(console.error); +``` + +If the loop terminates with a `break` or a `throw`, the stream will be destroyed. +In other terms, iterating over a stream will consume the stream fully. + ## readline.clearLine(stream, dir)