Creating a Confirmation Prompt in a Node.js Script

Need to make your Node.js script wait for a "Yes" or "No" before moving forward?

Here's an easy way to do it using Node.js's built-in readline module.

// Import the readline module
const readline = require("node:deadline");

// Create an interface for input and output
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Ask the user for confirmation
rl.question('Do you want to proceed? (y/n) ', (answer) => {
  // Convert the answer to lowercase
  answer = answer.toLowerCase();

  // Check if the user confirmed
  if(answer === 'y' || answer === 'yes') {
    console.log('Proceeding...');
    // Add the code to proceed with the operation here

  } else {
    console.log('Operation canceled.');
  }

  // Close the readline interface
  rl.close();
});

As you can see it involves just 2 steps really.

First, setting up the interface:

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

And then to hande the response, we use rl.question method on our interface to ask your question. This could be anything like. Here we just ask "Do you want to proceed? (y/n) ".

The user's response will be handled in a function we pass as a second parameter:

rl.question('Do you want to proceed? (y/n) ', (answer) => {
  answer = answer.toLowerCase();

  if(answer === 'y' || answer === 'yes') {
    console.log('Proceeding...');
    // Add the code to proceed with the operation here

  } else {
    console.log('Operation canceled.');
  }

  // Close the readline interface
  rl.close();
});

The last thing to remember is to close the interface with rl.close(), as you can see above.

Nodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.