process.stdin
is Node’s way of getting data that’s passed into it from outside. stdin
, short for “standard in”, is the path by which we can pass data into an application. This is usually text data that the user has typed, but it can also come from another application. A simple example of this would be:
$: cat "This is some text!" | node app.js
cat
is a unix program that simply combines text from one or more files (or from directly typing in some text, as above), and spits out the result. The vertical bar, or pipe operator, means that we’re connecting the output from cat
to the input of node app.js
. Whatever is output from cat
will be available as the stdin
of app.js
.
As you’ve noticed, the way we get this data is a little strange. The process.stdin
object has the function .on()
, which lets us add event handlers just like you would in the browser. Remember jQuery?
$('#button').on('click', function(event) {
console.log("You clicked a button!")
})
What you’re seeing is an event handler for the data
event.
process.stdin.on ("data", someFunction);
In plain English, this can be read as, when process.stdin receives some data, perform someFunction(). In your case, it’s adding the text coming in from stdin
to a variable called stdin_input
. Later,
process.stdin.on ("end", someOtherFunction)
This says, when process.stdin receives the signal that there’s no more input, perform someOtherFunction().