Skip to content

Instantly share code, notes, and snippets.

@image72
Forked from mauroao/readLineAssync.js
Created July 28, 2023 16:09
Show Gist options
  • Save image72/e7b68ac28f31158599e7b751ea26b91b to your computer and use it in GitHub Desktop.
Save image72/e7b68ac28f31158599e7b751ea26b91b to your computer and use it in GitHub Desktop.
Node.js - Read line from stdin asynchronously (async / await)
const readline = require('readline');
const readLineAsync = () => {
const rl = readline.createInterface({
input: process.stdin
});
return new Promise((resolve) => {
rl.prompt();
rl.on('line', (line) => {
rl.close();
resolve(line);
});
});
};
const run = async () => {
console.log('what is your name ? ');
const line = await readLineAsync();
console.log(`Your name is ${line}`);
};
run();
@image72
Copy link
Author

image72 commented Jul 28, 2023

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)
}

@image72
Copy link
Author

image72 commented Jul 28, 2023

https://stackoverflow.com/questions/43638105/how-to-get-synchronous-readline-or-simulate-it-using-async-in-nodejs/54269197#54269197

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment