Accessing Inputs with Node.js Standard Input

One question to ask on seeing the topic is, what is standard input? Using the human body to answer we can say that the human body needs a place to take in food which is through the mouth. Like the human body, every computer program running on Linux/UNIX based terminal needs a way to accept user input. That is usually through the keyboard. This is the standard input. Node.js has a method that accepts user input. This method is the stdin found in the global process module

The stdin Method

To access a one-line user input from the keyboard in the program, the process.stdin method which is an instance of Node.js readable stream is called, with the once event listener function attached to it. The once event listener accepts an event name and then a listener function. An example is below.

process.stdin.once('data', (data) => {
    // Code to perform an action
})

The event name is data. The data event name is emitted once the user completes typing in the input and clicks on the enter button to send it. The once event listener listens for the data event from the process.stdin. Once the event is emitted from the process.stdin. The listener function which is a callback function collects the incoming data from the terminal as an argument. Below is a function where the incoming input is displayed in the terminal.

process.stdin.once('data', (data) => {
    console.log(data)
})

So copy and save the code in a javascript file. Run the code by opening the terminal and typing node <name_of_the_file>.js. Please ensure the path of your terminal is in the same location as your file.

I guess you ran the code and realised you are stuck in the program. Ooops, sorry. You can use the combination of ctrl and c keys to end the program. This is done by pressing the Ctrl key and then the c key while still pressing the Ctrl button.

To end the program after it is done with accepting user input and running the listener function. The exit method of the process global module is called. This terminates the running program as soon as possible. The exit method is at the bottom of the callback function, to ensure every part of the program runs before we leave.

So our program looks like this:

process.stdin.once('data', (data) => {
    console.log(data)

    process.exit()
})

Conclusion

This article looks at the Node.js implementation of standard input using the process.stdin method to accept keyboard inputs for programs that run on the terminal. Thanks for reading, I hope you love it. Will like to read your comments about the article.