Node JS Get User Input From Command Line Prompt Example

If you are a beginner to Node.js, you must want to know which function can read user input from the command line. Just like the input() function in Python. This example will show you how to get user input data from the command line in Node.js application. One way is to use Node.js build-in process.stdin object or readline module, the other way is to use a Node.js third-party prompt module.

1. Use Node.js Process Object’s Stdin.

// Get process.stdin as the standard input object.
var standard_input = process.stdin;

// Set input character encoding.
standard_input.setEncoding('utf-8');

// Prompt user to input data in console.
console.log("Please input text in command line.");

// When user input data and click enter key.
standard_input.on('data', function (data) {

    // User input exit.
    if(data === 'exit\n'){
        // Program exit.
        console.log("User input complete, program exit.");
        process.exit();
    }else
    {
        // Print user input in console.
        console.log('User Input Data : ' + data);
    }
});

Save the above source code in a js file and execute the js in Node.js like below.

$ node get-user-input-from-command-line-prompt.js
Please input text in command line.
hello node js
User Input Data : hello node js

i love node 
User Input Data : i love node

exit
User input complete, program exit.

2. Use Node.js Built-In readline Module.

The readline module is Node.js built-in module, you can use it directly in your Node.js application like below.

// Import the Node.js readline module.
const readline = require("readline");

// Create an instance of readline interface.
const read_line_interface = readline.createInterface({
    // Assign process.stdin as input.
    input: process.stdin,
    // Assign process.stdout as output. 
    output: process.stdout
});

// Prompt one line question and read user input to variable status.
read_line_interface.question("How are you ? ", function(status) {

    // Prompt another line question and read user input to variable age.
    read_line_interface.question("How old are you ? ", function(age) {
        
        // Print user input data in the console.
        console.log(`I am ${status}, i am ${age} old`);

        // Close readline interface.
        read_line_interface.close();
    });
});

// When the readline prompt is closed, it will trigger this function.
read_line_interface.on("close", function() {
    // Print have a nice day on the console.
    console.log("\nHave a nice day !!!");
    // Exit the process.
    process.exit(0);
});

Save the above code in a Node.js file (test.js), and run it in a terminal like below.

$ node test.js
How are you ? fine
How old are you ? 25
I am fine, i am 25 old

Have a nice day !!!

3. Use Node.js Prompt Module.

Prompt is a third-party node module in npm repository. Before you can use it, you need to install the module into your project folder use the below command. You can read How To Use Node Package Manager to learn more about node js module management examples.

cd < Your node js current project directory >
npm install prompt

After install, you can see a node_modules folder is created in the current project directory. Be sure you run the above command in the current project folder.

node-module-folder-created-in-current-project-directory

Use Node.js Prompt module to get user input from command line example code.

// Include prompt module.
var prompt = require('prompt');

// This json object is used to configure what data will be retrieved from command line.
var prompt_attributes = [
    {
        // The fist input text is assigned to username variable.
        name: 'username',
        // The username must match below regular expression.
        validator: /^[a-zA-Z\s\-]+$/,
        // If username is not valid then prompt below message.
        warning: 'Username is not valid, it can only contains letters, spaces, or dashes'
    },
    {
        // The second input text is assigned to password variable.
        name: 'password',
        // Do not show password when user input.
        hidden: true
    },
    {
        // The third input text is assigned to email variable.
        name: 'email',
        // Display email address when user input.
        hidden: false
    }
];

// Start the prompt to read user input.
prompt.start();

// Prompt and get user input then display those data in console.
prompt.get(prompt_attributes, function (err, result) {
    if (err) {
        console.log(err);
        return 1;
    }else {
        console.log('Command-line received data:');

        // Get user input from result object.
        var username = result.username;
        var password = result.password;
        var email = result.email;
        var message = "  Username : " + username + " , Password : " + password + " , Email : " + email;

        // Display user input in console log.
        console.log(message);
    }
});

Below is the output when executing the above code.

$ node get-user-input-from-command-line-prompt.js 

prompt: username: jerry

prompt: password: 

prompt: email:  [email protected]

Command-line received data:

  Username : jerry , Password : 111111 , Email : [email protected]
0 0 vote
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Bill
Bill

I used your example 1 Use Node JS Process Object’s Stdin and tried to run this in Node and it will not exit no matter what I use in the If portion of the statement it will not execute anything in the if block. It will only execute the else portion of the block. what is wrong with the code? I have tried to copy and paste just as it is. I have also tried to change it nothing I do gets the if statement or what can make it to run?

Walter
Walter
Reply to  Bill

On Windows, the \n should be \r\n.

isaac marathon
isaac marathon
Reply to  Bill

Any way to remove the /n in example 1?

3
0
Would love your thoughts, please comment.x
()
x