From a0a3095aab402884f4e893112982b386989f15df Mon Sep 17 00:00:00 2001 From: Timothy Gu Date: Fri, 26 Oct 2018 17:53:04 -0700 Subject: [PATCH] readline: add support for async iteration Co-authored-by: Ivan Filenko Fixes: https://github.com/nodejs/node/issues/18603 Refs: https://github.com/nodejs/node/pull/18904 PR-URL: https://github.com/nodejs/node/pull/23916 Reviewed-By: Matteo Collina Reviewed-By: Gus Caplan --- doc/api/readline.md | 70 ++++++++++++++++- lib/readline.js | 43 ++++++++++ ...t-readline-async-iterators-backpressure.js | 48 ++++++++++++ .../test-readline-async-iterators-destroy.js | 78 +++++++++++++++++++ .../parallel/test-readline-async-iterators.js | 77 ++++++++++++++++++ tools/doc/type-parser.js | 2 +- 6 files changed, 315 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-readline-async-iterators-backpressure.js create mode 100644 test/parallel/test-readline-async-iterators-destroy.js create mode 100644 test/parallel/test-readline-async-iterators.js diff --git a/doc/api/readline.md b/doc/api/readline.md index 7250588f943f24..5882e36341d783 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -309,6 +309,43 @@ 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\[Symbol.asyncIterator\]() + + +> Stability: 1 - Experimental + +* Returns: {AsyncIterator} + +Create an `AsyncIterator` object that iterates through each line in the input +stream as a string. This method allows asynchronous iteration of +`readline.Interface` objects through `for`-`await`-`of` loops. + +Errors in the input stream are not forwarded. + +If the loop is terminated with `break`, `throw`, or `return`, +[`rl.close()`][] will be called. In other words, iterating over a +`readline.Interface` will always consume the input stream fully. + +A caveat with using this experimental API is that the performance is +currently not on par with the traditional `'line'` event API, and thus it is +not recommended for performance-sensitive applications. We expect this +situation to improve in the future. + +```js +async function processLineByLine() { + const rl = readline.createInterface({ + // ... + }); + + for await (const line of rl) { + // Each line in the readline input will be successively available here as + // `line`. + } +} +``` + ## readline.clearLine(stream, dir)