Last active
February 15, 2016 13:23
-
-
Save voidabhi/98510277f7f16ee31dbd to your computer and use it in GitHub Desktop.
Simple command line utility in node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
function parseArg(opt) { | |
var args = Array.prototype.slice.call(process.argv, 2); | |
var matches = args.filter(function(arg) { | |
return arg.indexOf(opt) > -1; | |
}); | |
if (Array.isArray(matches) && matches.length) { | |
return matches[0].split('=')[1]; | |
} | |
} | |
function main(dirpath) { | |
var usageDie = function(msg) { | |
console.error("error: " + msg); | |
console.error(); | |
console.error("usage: " + process.argv[0] + " --path=dirpath"); | |
console.error(); | |
console.error(" --path=dirpath\t- Path of the directory"); | |
console.error(" --help\t- Help"); | |
process.exit(1); | |
}; | |
dirpath = dirpath || parseArg('--path', '.'); | |
if (!dirpath) usageDie('invalid directory path'); | |
fs.readdir(dirpath, function(err, items) { | |
if (err) { | |
console.error(err); | |
return; | |
} | |
for (var i=0; i<items.length; i++) { | |
console.log(items[i]); | |
} | |
}); | |
return; | |
} | |
if (require.main === module) { | |
main(); | |
} | |
module.exports = main; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment