# Node.js equivalent of cat -n or nl

To add line numbers to a file (via stdin to stdout) we can use cat -n or nl.

Given the file test.txt with:

hello
hello
bye


We can do:

\$ cat -n < test.txt
1  hello
2  hello
3  bye


In languages like AWK, Perl, and Ruby, we often get built-in constructs to process files line-by-line, making this program trivial to write. Here is what I have in Ruby:

line_number = 0;
ARGF.each {|line| printf("%6d\t%s", line_number += 1, line)}


and granted, in AWK, it is much simpler since the line number is already present.

I've just tried to write this same script in node.js but found myself having to import the built-in fs module and then import three separate third-party modules. My solution is:

var fs = require('fs');
var through = require('through');
var split = require('split');
var sprintf = require('sprintf').sprintf;

var linenum = 0;

var number = through(function (line) {
this.queue(sprintf('%6d\t%s\n', ++linenum, line));
});

process.stdin.pipe(split()).pipe(number).pipe(process.stdout);


This is not intended to be a code-golfing problem, but rather a question of whether I have missed some built-in support for doing this kind of thing in node. I like the separation of concerns, but what I thought would be a simple script in node turned out rather long. Can it be improved?

It seems you need through and split to do the piping right. You do not need sprintf as you could build the number formatting yourself. You also do not need fs, you do not use it anywhere.

Something like

var through = require('through');
var split = require('split');

var linenum = 0;

function alignRight( s, n )
{
s = s + "";
return s.length > n ? s : new Array( n - s.length + 1 ).join(" ") + s;
}

var number = through(function (line) {
this.queue( alignRight( ++linenum, 6 ) + "\t" + line + "\n"  );
});

process.stdin.pipe(split()).pipe(number).pipe(process.stdout);


Does the trick for me. While it seems overkill, the nice thing is that you can pipe data between functions yourself, not needing to rely on the OS shell.

• Really really Nice! – Thomas Junk Aug 2 '14 at 11:19