PRO 30% Free • Stripe ($15) & Razorpay (₹899)

Getting User Input in Node.js

Top Course Staff · 2 min read · Web development · PRO · 30% Free Preview Available

Getting User Input in Node.js

Synchronous Input

Node.jsallows you to runJavaScriptcode outside of a browser window, offering powerful tools to interact with a computer filesystem, run web servers, and create terminal applications. Node handles these tasks by runningasynchronously, which means that reading user input from a terminal isn’t as simple as calling agetInput()function. In this article, we’ll show you an easy way around that (and some tips and tricks for handling user input) by using a helpful Node module.

Working with Input

Node.js provides a few ways to handle interactions, including the built-inprocessobject andreadlinemodule. While these are powerful tools, they rely oncallback functionsand can be confusing to work with at first.

const readline = require('readline').createInterface({  input: process.stdin,  output: process.stdout});
readline.question('Who are you?', name => {  console.log(`Hey there ${name}!`);  readline.close();});
Copy to clipboard
const readline = require('readline').createInterface({  input: process.stdin,  output: process.stdout});
readline.question('Who are you?', name => {  console.log(`Hey there ${name}!`);  readline.close();});

Running this code in Node, you’d see:

$ node read.jsWho are you?> 
Copy to clipboard
$ node read.jsWho are you?>

Then you could enter your input based on the prompt and see the response:

$ node read.jsWho are you?> CodecademyHey there Codecademy!$
Copy to clipboard
$ node read.jsWho are you?> CodecademyHey there Codecademy!$

This works as intended, but it’s a lot of boilerplate, and you need to callreadline.question()and create a callback function every time you want to use it for input. There’s a simpler way, whether you’re just getting started out with JavaScript development or just want to get an interactive script running as quickly as possible.

Usingprompt-sync

Theprompt-syncNode moduleprovides an easy-to-use alternative to this callback-based syntax.

  • Make sure you have Node and NPM installed
  • Runnpm install prompt-syncin the terminal
const prompt = require('prompt-sync')();
Copy to clipboard
const prompt = require('prompt-sync')();

Notice the extra()afterrequire(). Theprompt-syncmodule is a function that creates prompting functions, so you need to callprompt-syncin order to get your actual prompting function.

Once you’ve loaded theprompt-syncmodule and called it, using it to retrieve user input is relatively straightforward:

const prompt = require('prompt-sync')();
const name = prompt('What is your name?');console.log(`Hey there ${name}`);
Copy to clipboard
const prompt = require('prompt-sync')();
const name = prompt('What is your name?');console.log(`Hey there ${name}`);

Theprompt()function returns the user feedback, so simply store that return value to a variable to use it later. In the example above, thenamevariable stores the value, and it is then repeated to the user on the next line.

Letting Users Exit

By default, most terminal programs will exit withCtrl+C(This sends aSIGINT, or “signal interrupt” message indicating that a user wants to exit a program). Withprompt-sync, in order to make sure that your users can exit at will, add a configuration object withsigint: truewhen invoking theprompt-syncfunction:

const prompt = require('prompt-sync')({sigint: true});
Copy to clipboard
const prompt = require('prompt-sync')({sigint: true});

Working with Numbers

All user input will be read as a String, so in order to treat user input as numbers, you’ll need to convert the input:

const num = prompt('Enter a number: ');console.log('Your number + 4 =');console.log(Number(num) + 4);
Copy to clipboard
const num = prompt('Enter a number: ');console.log('Your number + 4 =');console.log(Number(num) + 4);

Making a basic app

The code below creates a small number guessing application.

const prompt = require('prompt-sync')({sigint: true});
// Random number from 1 - 10const numberToGuess = Math.floor(Math.random() * 10) + 1;// This variable is used to determine if the app should continue prompting the user for inputlet foundCorrectNumber = false;
while (!foundCorrectNumber) {  // Get user input  let guess = prompt('Guess a number from 1 to 10: ');  // Convert the string input to a number  guess = Number(guess);
  // Compare the guess to the secret answer and let the user know.  if (guess === numberToGuess) {    console.log('Congrats, you got it!');    foundCorrectNumber = true;  } else {    console.log('Sorry, guess again!');  }}
Copy to clipboard
const prompt = require('prompt-sync')({sigint: true});
// Random number from 1 - 10const numberToGuess = Math.floor(Math.random() * 10) + 1;// This variable is used to determine if the app should continue prompting the user for inputlet foundCorrectNumber = false;
while (!foundCorrectNumber) {  // Get user input  let guess = prompt('Guess a number from 1 to 10: ');  // Convert the string input to a number  guess = Number(guess);
  // Compare the guess to the secret answer and let the user know.  if (guess === numberToGuess) {    console.log('Congrats, you got it!');    foundCorrectNumber = true;  } else {    console.log('Sorry, guess again!');  }}

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

30% Free Preview Reached · Unlock Remaining 70%

Complete Payment to Unlock Full Guide & Source Code

You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.

✓ Full Access to All 160+ Projects
✓ Instant Blur Removal Everywhere
✓ Production Source Code & Blueprints
✓ All Future Deep Dives Included
Instant Unhindered Activation ·
End of Preview · Unlock Complete Blueprint & Source Code

Ready to access the complete step-by-step tutorial?

Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.

Production AI Blueprints

Ready to build production-grade AI systems?

Enjoyed this guide? Continue exploring our library of 166+ production blueprints, multi-agent swarms, and autonomous agent systems with 100% unblurred, executable source code.