Matt Wilson Matt Wilson - 5 months ago 11
Node.js Question

How to read from stdin line by line in Node

I'm looking to process a text file with node using a command line call like:

node app.js < input.txt


Each line of the file needs to be processed individually, but once processed the input line can be forgotten.

Using the on-data listener of the stdin, I get the input steam chunked by a byte size so I set this up.

process.stdin.resume();
process.stdin.setEncoding('utf8');

var lingeringLine = "";

process.stdin.on('data', function(chunk) {
lines = chunk.split("\n");

lines[0] = lingeringLine + lines[0];
lingeringLine = lines.pop();

lines.forEach(processLine);
});

process.stdin.on('end', function() {
processLine(lingeringLine);
});


But this seems so sloppy. Having to massage around the fist and last items of the lines array. Is there not a more elegant way to do this?

Answer

You can use the readline module to read from stdin line by line:

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

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