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?