Created
October 24, 2024 15:35
-
-
Save lejonmanen/10ad481f0d13a97e44ff8b505f10d95e to your computer and use it in GitHub Desktop.
Read input from user in terminal, Node.js
This file contains hidden or 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
| /* | |
| Use this file in your project. | |
| But first, create a Node project: | |
| npm init -y | |
| Then add a line to package.json: | |
| "type": "module", | |
| Usage: | |
| import { ask } from './ask.js' | |
| let answer = await ask("Hello, what's your name? ") | |
| */ | |
| 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 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment