Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active October 24, 2024 15:32
Show Gist options
  • Save lejonmanen/b5c9c033a8fd30b9f30884dfe97012c8 to your computer and use it in GitHub Desktop.
Save lejonmanen/b5c9c033a8fd30b9f30884dfe97012c8 to your computer and use it in GitHub Desktop.
Using Node.js async readline
import readline from 'node:readline'
async function ask(query) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, tabSize: 4 });
return new Promise((resolve) => rl.question(query, (answer) => {
rl.close();
resolve(answer);
}));
}
export { ask }
import { getQuestion } from './readline.js'
const [question, close] = getQuestion()
let input = await question('Please input a number')
console.log(`The number is: ${input}.`)
close()
import readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process'
function getQuestion() {
const rl = readline.createInterface({ input, output });
return [rl.question.bind(rl), rl.close.bind(rl)]
// Use like this:
// const [question, close] = getQuestion()
}
const [question, close] = getQuestion()
let answer = await question('What do you think of Node.js? ');
// You can use question multiple times. But don't forget to close when you're done.
console.log(`Thank you for your valuable feedback: ${answer}`);
close()
import readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process'
function getQuestion() {
const rl = readline.createInterface({ input, output });
return [rl.question.bind(rl), rl.close.bind(rl)]
// Use like this:
// const [question, close] = getQuestion()
}
export { getQuestion }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment