Accept input from the command line in Node

How to use the built-in readline node module to make Node.js CLI programs interactive

How to make Node.js CLI programs interactive?

Nodes available since version 7readlineModuleTo do this exactly: from a readable stream (e.g.process.stdinStream, which is terminal input during the execution of the Node program, only one line at a time.

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

readline.question(What's your name?, (name) => { console.log(Hi </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">name</span><span style="color:#e6db74">}</span><span style="color:#e6db74">!) readline.close() })

This code asks for the username, and once the text is entered and the user presses the Enter key, we will send a greeting.

Thisquestion()The method displays the first parameter (question) and waits for user input. Once the enter key is pressed, it will call the callback function.

In this callback function, we close the readline interface.

readlineSeveral other methods are provided, and I will let you check in the package documentation linked above.

If you need a password, it is best not to echo it, but to display a password.*Symbolic.

The easiest way is to usereadline-syncpackageAs far as the API is concerned, this is very similar and can be processed immediately.

The third party provides a more complete and abstract solutionInquirer.js package.

You can install usingnpm install inquirer, And then you can copy the above code like this:

const inquirer = require('inquirer')

var questions = [{ type: ‘input’, name: ‘name’, message: “What’s your name?”, }]

inquirer.prompt(questions).then(answers => { console.log(Hi </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">answers</span>[<span style="color:#e6db74">'name'</span>]<span style="color:#e6db74">}</span><span style="color:#e6db74">!) })

Inquirer.js allows you to perform many operations, such as asking for multiple choices, radio buttons, confirmations, etc.

It is worth mentioning all the alternatives, especially the built-in alternatives provided by Node, but if you plan to take CLI input to a new level, then Inquirer.js is the best choice.

Download mine for freeNode.js manual


More node tutorials: