Skip to content

Instantly share code, notes, and snippets.

@akoenig
Last active August 29, 2015 13:57
Show Gist options
  • Save akoenig/9377410 to your computer and use it in GitHub Desktop.
Save akoenig/9377410 to your computer and use it in GitHub Desktop.
A super-duper-tiny LOC counter (with no external dependencies).
#!/usr/bin/env node
'use strict';
/**
*
* A super-duper-tiny LOC counter (with no external dependencies).
*
* Usage: loc "path" "extension-to-filter"
*
* Example: loc "/home/akoenig/projects/a" "js"
*
* @author André König ([email protected])
* @version 0.1.0
*
*/
var fs = require('fs'),
path = require('path'),
readline = require('readline');
/**
* Recursive directory walker.
*
*/
function walker (dir, extension, next) {
var results = [],
opens;
if (!extension) {
return next(new Error('Please define a file extension.'))
}
fs.readdir(dir, function (err, list) {
if (err) {
return next(err);
}
opens = list.length;
if (!opens) {
return next(null, results);
}
list.forEach(function (file) {
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walker(file, extension, function(err, res) {
results = results.concat(res);
if (!--opens) {
return next(null, results);
}
});
} else {
if (('.' + extension) === path.extname(file)) {
results.push(file);
}
if (!--opens) {
return next(null, results);
}
}
});
});
});
}
module.exports = (function () {
var directory = process.argv[2],
extension = process.argv[3];
if (!directory || !extension) {
return console.error('Please define the necessary arguments\n\n Usage: loc "path" "extension-to-filter"\n Example: loc "/home/akoenig/projects/a" "js"');
}
walker(directory, extension, function onWalked (err, files) {
var i = 0,
len = files.length;
function next () {
var file = files.pop(),
reader;
if (file) {
reader = readline.createInterface({
input: fs.createReadStream(file),
output: process.stdout,
terminal: false
});
reader.on('line', function(line) {
i = i + 1;
});
reader.on('close', next);
} else {
console.log('Summary: %d LOC in %d files', i, len);
}
}
next();
});
})();
{
"name": "loc",
"version": "0.1.0",
"author": "André König ([email protected])",
"bin": {
"loc": "./loc.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment