readline in node for processing stdin & stdout

2020-04-10

 | 

~2 min read

 | 

352 words

I haven’t had many opportunities to play around with building CLIs or reading data from STDIN with Node in a while, so today I decided to play around and found the readline module of Node.

Using it to process data fed into an application from the command line was much simpler than I expected!

src/index.js
const readline = require("readline")

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

rl.on("line", (input) => {
  console.log(`the input is -->${input}`)
})

rl.on("close", () => {
  console.log(`That's all folks!`)
})

Then, to start the program,

$ node src/index.js

The program will then await stdin input. For example:

TESTING # My first input
the input is --> TESTING
MY STREAM WORKS! # My second input
the input is --> MY STREAM WORKS!

Since the process stays alive, we need to terminate it somehow to have the readline emit the end event. I accomplished this by quitting the application (ctrl+c):

That's all folks!

If typing the input by hand is annoying, this is a good opportunity to take advantage of piping in inputs:

$ cat mySampleInput.txt | node src/index.js

In this case, each new line of the mySampleInput text file will be fed into the Node app. When the last line is read, the close event will be emitted automatically and the farewell “That’s all folks!” will be printed.

Finally, if instead of printing the output to the terminal, we wanted it in a file, it’d be a matter of redirecting the output.

$ mkdir -p output
$ touch output/mySampleOutput.txt
$ cat mySampleInput.txt | node src/index.js > output/mySampleOutput.txt

That’s it for now! I’ve been looking at doing more scripting and digging around Python a little bit of late, so hope to have more opportunities to explore the space in the future. Until then, it’s nice to know that I can handle many cases easily with Node. It simply requires stepping outside of my web app world and thinking about the problem a bit differently.

For more, check out the Node documentation which includes two tiny demos as well.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!