In this post, I am going to write a simple Node.js program that prompts the user for input and then prints it out to the console:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter some text: ', (answer) => {
console.log(`You entered: ${answer}`);
rl.close();
});
Here’s what this code does:
- It uses Node.js’s built-in
readlinemodule to create an interface for reading user input and writing output. - It creates an instance of the interface by calling
readline.createInterface(), passing inprocess.stdin(which represents the standard input stream) as the input andprocess.stdout(which represents the standard output stream) as the output. - It calls the
rl.question()method to prompt the user for input. This method takes two arguments: the prompt to display to the user, and a callback function to run when the user enters a line of input. - The callback function logs the user’s input to the console using
console.log(), and then closes the interface usingrl.close().
To run this program, save the code to a file (e.g. index.js) and run it with Node.js by typing node index.js in your terminal.