Read Lines from stdin in Node.js

It is easy to write a hello world program in Node.js:

console.log("Hello world!")

However, due to the asynchronous nature of Javascript, reading inputs and writing outputs are less straight-forward. We have to pass the callback functions or register event listeners.

First Attempt

For example, to read some data from standard input, we have to write:

process.stdin.on('data', function (data) {
  console.log(data.length);
});

In this example, process is the global hosting object of Javascript environment in Node.js, and process.stdin is an instance of ReadStream. The .on() function call registers a callback for data event. The callback function will be invoked when data are available.

If we run this example with node test.js and type the input manually, then it will seem to work:

$ node test.js
aa
3
bbbb
5

But it does not always work. It is just a coincident to receive a data event when we hit the Enter key. For example, if we pipe the standard input, then we will see a completely different output:

$ printf "aa\nbbbb\n" | node test.js
8

Corrent Answer

So, how do we read lines from standard input? The answer is to wrap process.stdin with a readline interface. For example:

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function (line) {
  console.log(line.length);
});

We import readline module and invoke readline.createInterface() to create a wrapper interface. Besides, we are listening to line event instead of data event now. There is one pitfall: you might wish to specify terminal: false, otherwise some extra output will be printed to standard output.

Here's the output:

$ printf "aa\nbbbb\n" | node test.js
2
4

If you remove terminal: false from the options, then you will see:

$ printf "aa\nbbbb\n" | node test.js
aa
2
bbbb
4

In this post, we introduced the basic usage of Stream and Readline module in Node.js. Check the links in the Reference section for further information.