Nodejs: first impression

Nodejs is incredible, especially for a front-end developer. what is Node,
I just quote from website:

Node.js is a platform built on Chrome’s JavaScript runtime for easily
building fast, scalable network applications. Node.js uses an
event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for data-intensive real-time applications that run
across distributed devices.

After some digging, I wrote a simple wc clone, here is it:

wc.jsview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env node

/**
* simple wc clone written in JS.
* need optimist for options parsing.
* Sian Cao <[email protected]>
*/


var argv = require('optimist')
.usage('Usage: $0 [OPTION]... [FILE]...\n' +
' -c count chars\n' +
' -l count lines\n' +
' -w count words')
.boolean(['c', 'l', 'w', 'h'])
.argv,
fs = require('fs'),
util = require('util');

function processChunk(chunk, collects) {
var i = 0, inword = false;
for (i = 0; i < chunk.length; i += 1) {
collects.nr_chars += 1;
if (/\w/.test(chunk[i])) {
if (!inword) {
inword = true;
collects.nr_words += 1;
}
} else {
inword = false;
}

if (chunk[i] == '\n') {
inword = true;
collects.nr_lines += 1;
}
}
}

function printCounts(collects) {
if (argv.l) {
util.print(collects.nr_lines + ' ');
}

if (argv.w) {
util.print(collects.nr_words + ' ');
}

if (argv.c) {
util.print(collects.nr_chars + ' ');
}

if (!(argv.l || argv.c || argv.w)) {
util.print(collects.nr_lines + ' ' + collects.nr_words + ' ' + collects.nr_chars);
}

util.print('\n');
}

if (argv.h || argv.help) {
require('optimist').showHelp();
process.exit(0);
}

if (argv._.length > 0) {
argv._.forEach(function(file) {
var collects = {
nr_lines: 0,
nr_words: 0,
nr_chars: 0
};

var fstat = fs.statSync(file);
if (fstat.isFile()) {
fs.createReadStream(file, {encoding: 'utf8'}).on('data', function(chunk) {
processChunk(chunk, collects);

}).on('end', function() {
printCounts(collects);
});
}
});

} else {
(function() {
var collects = {
nr_lines: 0,
nr_words: 0,
nr_chars: 0
};

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function(chunk) {
processChunk(chunk, collects);
});

process.stdin.on('end', function() {
printCounts(collects);
});
})();
}

You need to install optimist npm install optimist to run this file.

update:
a really great sum-up of resources for you to dive into node