Unix wc clone in Node.js

I have been trying to learn NodeJS a bit lately. I have found a good exercise to learn new language is to re-implement UNIX utilities. I decided to try to re-implement ‘wc’, which counts the number of words, characters, and lines that are received on stdin.

The code isn’t perfect, in that it doesn’t match the exact output of wc, but I am happy with it. The main thing I wanted to do is learn about Javascript closures, which this sample helped me to do. Note that the line_processor variable actually has four callable functions, but the ‘lines’, ‘characters’, and ‘words’ variables are all inaccessible outside of the line_processor closure. This was a tricky concept for me to understand.


// Takes a stream of data and counts the number of words, lines, and characters
//
// Similar to the the UNIX program 'wc'

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

var line_processor = (function(){

var lines = 0;
var characters = 0;
var words = 0;

return {
update : function(line) {
// imperfect counting, but good enough
characters = characters + line.length;
lines++;
words = words + line.split(" ").length;
},
get_words: function() {
return words;
},
get_lines: function() {
return lines;
},
get_characters: function() {
return characters;
}
};
})();

rl.on('line', function(line) {
line_processor.update(line);
});
rl.on('close', function() {
console.log("Words: " + line_processor.get_words());
console.log("Lines: " + line_processor.get_lines());
console.log("Characters: " + line_processor.get_characters());
});

About samkerr

I'm an eclectic person. I like to dabble in a multitude of things. I'm sure you'll find my blog reflects that.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *