Categories
JavaScript Answers

How to read value from console interactively with Node.js?

Spread the love

Sometimes, we want to read value from console interactively with Node.js.

In this article, we’ll look at how to read value from console interactively with Node.js.

How to read value from console interactively with Node.js?

To read value from console interactively with Node.js, we can use the process.openStdin method.

For instance, we write

const stdin = process.openStdin();

stdin.addListener("data", (d) => {
  console.log(d.toString().trim())
});

to call process.openStdin to accept interactive input from the console.

Then we call stdin.addListener with 'data and a callback to get the entered data d.

The data event is emitted when input is entered.

In the callback, we convert the input data to a string with toString and trim the starting and ending whitespaces with trim.

Conclusion

To read value from console interactively with Node.js, we can use the process.openStdin method.

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 *