7
\$\begingroup\$

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?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jan 18, 2014 at 18:44
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.

answered Jan 27, 2014 at 13:47
\$\endgroup\$
1
  • \$\begingroup\$ Really really Nice! \$\endgroup\$ Commented Aug 2, 2014 at 11:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.