Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created October 24, 2024 15:35
Show Gist options
  • Select an option

  • Save lejonmanen/10ad481f0d13a97e44ff8b505f10d95e to your computer and use it in GitHub Desktop.

Select an option

Save lejonmanen/10ad481f0d13a97e44ff8b505f10d95e to your computer and use it in GitHub Desktop.
Read input from user in terminal, Node.js
/*
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