Read from console javascript

Get User Input from JavaScript Console

in this tutorial, We’ll learn how to get user input from the console using javascript or nodejs. I’ll discuss both ways Javascript and Nodejs to get user input from the console.

JavaScript’s prompt() method makes it simple to obtain user input from a web browser.

Getting user input from the browser console

You can use the prompt() method that the browser offers in order to request user input from it. The prompt() method can take user input in the form of a string and save it on a variable as seen below:

To let the user know what kind of input your application expects, the method additionally accepts a string as additional information.

const input = prompt("What's employee name?"); alert(Employee name is $);

Get User Input Using Nodejs

We can also get user input using NodeJS. It will require us to use the readline() package. With this package, we can then accept user input and even output it to the console.

  • string: This prompts the message to take input from the user.
  • callback(): This is a callback function or a call after the function that accepts an argument which is the user’s input.
Читайте также:  Typing text html script

How to use the readline()

You can import require() the module as follows:

const readline = require(«readline»)

An Interface object must be created and connected to an input stream. Readline is used to design the interface. When using the createInterface() method, supply an object parameter with the input and output options.

Here’s an example of creating the readline interface:

const readline = require("readline"); const r_interface = readline.createInterface(< input: process.stdin, output: process.stdout, >);

in the above code, we have used two methods: to get input by process.stdin method and print output using process.stdout .

  • The string question you want to ask your user
  • The options object (optional) where you can pass the ‘abort’ signal
  • The callback function to execute when the answer is received, passing the answer to the function
const readline = require("readline"); const r_interface = readline.createInterface(< input: process.stdin, output: process.stdout, >); r_interface.question("What is your age? ", function (inp) < console.log(`Your age is $`); r_interface.close(); >);

By using the r_interface.close() method within the callback function, you can close the r_interface interface:

Save the file as user_input.js and run the nodejs:

What is your age? 34 Your age is 34

Getting user input from NodeJS using prompt-sync

We also use nodejs prompt-sync module to get user input into console, We’ll install module using npm or Yarn as follows:

npm install prompt-sync # or yarn add prompt-sync

Sample use of prompt-sync

const prompt = require("prompt-sync")(); const input = prompt("What is your name? "); console.log(Your name is $);

Your Node instance will wait for the input before executing the next line. You can get more information from prompt-sync module documentation

Источник

How to get user input from JavaScript console

There are two ways of getting user input from JavaScript depending on whether you want to get the input from the browser or NodeJS. This tutorial will help you to learn both.

Getting user input from the browser console

To ask for user input from the browser, you need to use the prompt() method provided by the browser.

The prompt() method allows you to accept user input as a string and store it on a variable as follows:

The method also accepts a string as additional information to let the user know what kind of input your application is expecting.

For example, write the following code to ask for the user’s name:

 Or write the following hint when you need to know the user’s age:
  The prompt() will be displayed by the browser as follows:

Browser prompt example

Then the alert() method will show the result as follows:

Alert showing the result

You can style the string text as a question or a hint depending on your requirements.

Getting user input from the NodeJS console

To accept user input from NodeJS console, you need to use the provided readline module.

You can require() the module as follows:

Then, you need to create an Interface instance that is connected to an input stream. You create the Interface using readline.createInterface() method, while passing the input and output options as an object argument.

Because you want the input and output to be written to the console, you need to write the input as process.stdin and output as process.stdout

Here’s an example of creating the readline interface:

To ask for user input, you need to call the question() method from the Interface instance, which is assigned to rl variable on the code above.
  • The string question you want to ask your user
  • The options object (optional) where you can pass the ‘abort’ signal
  • The callback function to execute when the answer is received, passing the answer to the function

You can skip the options object and pass the callback function as the second parameter.

Here’s how you use question() the method:

 Finally, you can close the rl interface by calling the rl.close() method inside the callback function:
 Save the file as ask.js , then call the script using NodeJS like this:
    And that’s how you can ask for user input using NodeJS readline module.

You can also use the AbortController() from NodeJS to add a timer to your question and cancel it when a certain amount of time has passed.

But please be aware that the AbortController() method is only available for NodeJS version 15 and up. And even then, the method is still experimental.

The following question will be aborted when no answer was given in 10 seconds after the prompt. The code has been tested to work on NodeJS version 16.3.0 and up:

You can add the timer like in the code above for time-sensitive questions.

As you can see from the example above, the readline module is quite complex compared to the easy prompt() method from the browser.

Alternatively, you can use the npm prompt-sync module to ask for user input without using the readline module.

Getting user input from NodeJS using prompt-sync module

First, you need to install the prompt-sync module using npm or Yarn as follows:

Then, you just need to require() the prompt-sync module and use the prompt() method like in the browser.

Take a look at the code below:

 Since the method is synchronous, your Node instance will wait for the input before executing the next line. For more information, you can visit the prompt-sync module documentation 

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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.

Источник

Оцените статью