Accept input from the command line in Node.js
How to make a Node.js CLI program interactive?
Node.js since version 7 provides the readline
module to perform exactly this: get input from a readable stream such as the process.stdin
stream, which during the execution of a Node.js program is the terminal input, one line at a time.
const module "node:readline"
readline = var require: NodeJS.Require
(id: string) => any
require('node:readline');
const const rl: readline.Interface
rl = module "node:readline"
readline.function createInterface(options: readline.ReadLineOptions): readline.Interface (+1 overload)
createInterface({
ReadLineOptions.input: NodeJS.ReadableStream
input: var process: NodeJS.Process
process.NodeJS.Process.stdin: NodeJS.ReadStream & {
fd: 0;
}
stdin,
ReadLineOptions.output?: NodeJS.WritableStream | undefined
output: var process: NodeJS.Process
process.NodeJS.Process.stdout: NodeJS.WriteStream & {
fd: 1;
}
stdout,
});
const rl: readline.Interface
rl.Interface.question(query: string, callback: (answer: string) => void): void (+1 overload)
question(`What's your name?`, name: string
name => {
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(`Hi ${name: string
name}!`);
const rl: readline.Interface
rl.Interface.close(): void
close();
});
This piece of code asks the user's name, and once the text is entered and the user presses enter, we send a greeting.
The question()
method shows the first parameter (a question) and waits for the user input. It calls the callback function once enter is pressed.
In this callback function, we close the readline interface.
readline
offers several other methods, please check them out on the package documentation linked above.
If you need to require a password, it's best not to echo it back, but instead show a *
symbol.