Ввод из консоли javascript

How to read input from the command line in Node.js

Are you developing a little CLI tool in Node.js and want to be able to prompt users to enter input from the command line? Node.js provides the readline module precisely for this purpose. It offers an interface for reading data from a readable stream such as process.stdin , one line at a time.

Here is a simple example that prompts the user to input their name and nationality and then print these details on the console:

const readline = require('readline') const rl = readline.createInterface( input: process.stdin, output: process.stdout >) // ask the user for the name input rl.question(`What's your name? `, name =>  // ask for nationality rl.question(`What are you from? `, country =>  // log user details console.log(`$name> is from $country>`) // close the stream rl.close() >) >) 

In the above example, the readline.createInterface() method is used to create an instance of readline by defining readable and writable streams.

The rl.question() method displays the query (the question) and waits for the user to enter an answer. Once the input data is available, it calls the callback method passing the user’s input as the first parameter.

Finally, we call the rl.close() method in the final callback to close the readline interface. You can also listen to the close event invoked when the stream is closed. It can be useful to do some post questions work:

// listen for close event rl.on('close', () =>  console.log('Goodbye 👋') // exit the process process.exit(0) >) 

Read the readline documentation to learn more about all the available methods and events.

The readline module is a low-level Node.js package that you might think is too complicated for complex use cases. If you want a higher-level interface for handling user input, just use the prompt module from the Node Package Manager (NPM). You can add it to your project by executing the following command:

It is relatively easy to use prompt than the readline module. You don’t need to explicitly configure readable and writable streams. Let us rewrite the above example by using the prompt module:

const prompt = require('prompt') // start the prompt prompt.start() // ask the user for the input prompt.get(['name', 'country'], (err, result) =>  if (err)  throw err > // print user details console.log(`$result.name> is from $result.country>`) >) 

The prompt module makes it easier to securely ask the user to input a password. It will mask the input instead of showing the actual characters of the password:

const prompt = require('prompt') // start the prompt prompt.start() // define properties schema var schema =  properties:  name:  pattern: /^[a-zA-Z\s\-]+$/, message: 'Name must be only letters, spaces, or dashes', required: true >, password:  hidden: true > > > // ask the user for the input prompt.get(schema, (err, result) =>  if (err)  throw err > // print user credentials console.log(`$result.name> / $result.password>`) >) 

Notice the pattern attribute in the above example. It ensures that the input, we receive from the user for the name property, is validated before moving to the next property input.

The prompt module exposes another convenient method called addProperties() to extend an existing object by adding properties data from the command line:

const prompt = require('prompt') // start the prompt prompt.start() // create an object const user =  name: 'John Doe', country: 'USA' > // extend `user` object prompt.addProperties(user, ['email', 'age'], err =>  if (err)  throw err > // print modified object console.dir(user) >) 
$ node index.js prompt: email: john.doe@example.com prompt: age: 23  name: 'John Doe', country: 'USA', email: 'john.doe@example.com', age: '23' > 

As you can see above, prompt is highly customizable. Check out the official documentation for more information. prompt can be a good choice if you are planning to build a solid CLI tool in Node.js. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Reading Console Inputs in JavaScript

JavaScript is praised for its asynchronous nature and perfect handling of HTML but, by nature, JavaScript was built for working with the browser, so cli features weren’t really important issues until NodeJS came along. Because of this, most (if not all) tutorials always cover the sending of messages to the console but never collecting messages from it. In this article we will show different ways you can read inputs from the console.

Reading a Line

One of the types of inputs that can be read from the console is a line of text. This means that the console prompts the user to write an input and then the user writes a line of text and that line gets sent to the program when the user hits Enter.

Using readline module

This is a module provided by Node for handling console inputs and outputs and doesn’t need any installation before using. To use this module to receive inputs, we start by creating a new JavaScript file and importing the readline module.

const readline = require('readline'); 

Next, we create the console interface using the readline module’s createInterface function

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

The createInterface function takes an object which includes the input and the output that the interface connects to. After that, we can read inputs from the console like so:

rl.question('What is your name? ', ans =>  console.log('Your name is', ans); rl.close(); >); 

At the end of reading inputs from the console you need to close the interface using the rl.close() or else the program wouldn’t quit.

Making it a Promise

Reading from the console using the above method is good but it gets hard over time to track the flow of the program because the execution keeps travelling into different functions when you are getting more than one input from the console. To make it more elegant and easy to follow, we can make it a promise. To do this we start having our starting point in our code.

const readline = require('readline'); const rl = readline.createInterface( input: process.stdin, output: process.stdout, >); 

After this, we make it a promise by creating a function that returns a promise which gets resolved when the user has entered a text.

function question(text)  return new Promise(resolve =>  rl.question(text, resolve); >) > 
question("What is your name? ") .then(ans =>  console.log("Your name is", ans); rl.close(); >); 

Using Readline-sync

Reading lines from the console gets a bit complicated because of the asynchronous methods. It gets a bit hard to manage as the project so a synchronous method was developed. It makes reading from the console really easy and straightforward. We start by creating a folder and installing the readline-sync module with:

const rl = require('readline-sync'); 
const name = rl.question('What is your name? '); console.log('Your name is', name); 

This reads input from the console and returns the result. We also don’t have to close the interface before the program closes so it really makes the code look a lot cleaner.

Reading a Keypress

In the other sections, we covered the process of reading lines of text from the console and sending them using the Enter key. But there are times when we want to get just a single character from the console without ever needing the user to hit Enter. We begin with using the readline module, then we will talk about making it a promise and finally use the readline-sync module.

Readline module

const readline = require('readline'); readline.emitKeypressEvents(process.stdin); process.stdin.setRawMode(true); 
  1. It imports the readline module at the beginning,
  2. Then, set the standard input ( process.stdin ) to receive all key-press emit calls,
  3. And finally, enable raw mode of the standard input so users don’t have to hit Enter before the onKeyPress event is called.

Now, we can start handling key-press events with the following lines of code.

process.stdin.on('keypress', (character) =>  console.log(character); if (character === "k")  process.stdin.destroy(); > >); 

In the above snippet, the process.stdin.on() is used to listen to events emitted in process.stdin , and for listening to key hits we use the keypress event name. To close the console reading process and allow the program to exit, we put process.stdin.destroy(); in order to stop the standard input from receiving anymore characters and enable our code to terminate.

Making it a promise

We can make the above code more cleaner and elegant by converting it to a promise. It is a very easy task and just like the first time we will create a function that returns a promise which gets resolved when the event is triggered.

function keypress()  return new Promise( resolve =>  process.stdin.on('keypress', resolve); >); > 

And can now be used like so:

keypress() .then(character =>  console.log(character); >) .finally(() =>  process.stdin.destroy(); >); 

Using Readline-sync

Reading a single key hit using the readline-sync module is very simple. All we need to do is have the readline-sync module in your project directory. If you don’t know how to install it we use npm i readline-sync.

Next, we import the module into the code we want to use it in.

const rl = require('readline-sync'); 

And, read a key input from the console with the following.

const key = rl.keyIn(); console.log(key); 

Conclusion

Console inputs is one of the most rarely talked about concepts in JavaScript. So rare that only few people know how to do it. The best way to learn how to do it was to read the docs, and honestly, not all developers like to do that, so this article was created to help give a clearer and more straightforward tutorial to it.

Источник

Accept input from the command line 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.

This piece of code asks the user’s name, and once the text is entered and the user presses enter, we send a greeting.

The question() method shows the first parameter (a question) and waits for the user input. It calls the callback function once enter is pressed.

In this callback function, we close the readline interface.

readline offers several other methods, please check them out on the package documentation linked above.

If you need to require a password, it’s best not to echo it back, but instead show a * symbol.

The simplest way is to use the readline-sync package which is very similar in terms of the API and handles this out of the box.

A more complete and abstract solution is provided by the Inquirer.js package.

You can install it using npm install inquirer , and then you can replicate the above code like this:

Inquirer.js lets you do many things like asking multiple choices, having radio buttons, confirmations, and more.

It’s worth knowing all the alternatives, especially the built-in ones provided by Node.js, but if you plan to take CLI input to the next level, Inquirer.js is an optimal choice.

Источник

Читайте также:  Самые популярные фреймворки для php
Оцените статью