Categories
JavaScript Answers

How to read standard input with JavaScript?

Spread the love

Sometimes, we want to read standard input with JavaScript.

In this article, we’ll look at how to read standard input with JavaScript.

How to read standard input with JavaScript?

To read standard input with JavaScript, we can use the readline module.

For instance, we write:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout

});

rl.question("> >What's your name?  ", (answer) => {
  console.log("Hello", answer);
  rl.close();
});

We call readline.createInteface with:

{
  input: process.stdin,
  output: process.stdout

}

to read standard input and output standard output.

Then we call rl.question to show a prompt for the user.

And the entered answer will be set as the value of the answer parameter.

Finally, we call rl.close to stop reading standard input.

Conclusion

To read standard input with JavaScript, we can use the readline module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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