Last active
October 24, 2024 15:32
-
-
Save lejonmanen/b5c9c033a8fd30b9f30884dfe97012c8 to your computer and use it in GitHub Desktop.
Using Node.js async readline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getQuestion } from './readline.js' | |
const [question, close] = getQuestion() | |
let input = await question('Please input a number') | |
console.log(`The number is: ${input}.`) | |
close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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