Skip to content

Instantly share code, notes, and snippets.

@hanishi
Created January 24, 2013 03:36
Show Gist options
  • Save hanishi/4617422 to your computer and use it in GitHub Desktop.
Save hanishi/4617422 to your computer and use it in GitHub Desktop.
word_count
var fs = require('fs')
, completedTasks = 0
, tasks = []
, wordCounts = {}
, filesDir = './text';
function countWordsInText(text) {
var words = text.toString().toLowerCase().split(/\W+/).sort();
for (var index in words) {
var word = words[index];
if (word) {
wordCounts[word] = (wordCounts[word]) ?
wordCounts[word] + 1 : 1;
}
}
}
fs.readdir(filesDir, function (err, files) {
if (err) throw err;
for (var index in files) {
var task = (function (file){
return function() {
fs.readFile(file, function (err, text) {
if (err) throw err;
countWordsInText(text);
checkIfComplete();
});
}
})(filesDir + '/' + files[index]);
tasks.push(task);
}
for (var task in tasks) {
tasks[task]();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment