How to get synchronous readline, or “simulate” it using async, in nodejs?

Just in case someone stumbles upon here in future

Node 11.7 added support for this using async await

const readline = require('readline');
//const fileStream = fs.createReadStream('input.txt');

const rl = readline.createInterface({
  input: process.stdin, //or fileStream 
  output: process.stdout
});

for await (const line of rl) {
  console.log(line)
}

Remember to wrap it in async function(){} otherwise you will get a reserved_keyword_error.

const start = async () =>{
    for await (const line of rl) {
        console.log(line)
    }
}
start()

To read an individual line, you can use the async iterator manually

const it = rl[Symbol.asyncIterator]();
const line1 = await it.next();

Leave a Comment