Programming

Accept input from the command line in Node.js

In other programming languages, it’s easy to take input from the command line. Like in Python you can do it using the input function. The program will be like a = input(“Enter a value: ”) or in C++ it will be cin >> a; but how to do that on JavaScript or in Node.js?

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.

Read More: JavaScript Loan Calculator Project 

const inquirer = require('inquirer');

const questions = [
  {
    type: 'input',
    name: 'name',
    message: "What's your name?",
  },
];

inquirer.prompt(questions).then(answers => {
  console.log(`Hi ${answers.name}!`);
});

 

This piece of code will ask a user what’s his/her name. And if the user enters his/her name and press enter the value will be stored in a variable. In this case, the variable name is ‘name’ and after that, a callback function will be called. In this case, we console.log a greeting message and after that, we close the readline interface.

node.js

The question() method shows the first parameter (a question) and waits for the user input. So, this is the whole process to take input from the command line in Node.js or from JavaScript.



What is your reaction?

0
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly

Leave a reply

Your email address will not be published. Required fields are marked *