Matt Wilson Matt Wilson - 4 months ago 5x
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.


var lingeringLine = "";

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

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


process.stdin.on('end', function() {

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?


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){