Skip to content

Instantly share code, notes, and snippets.

@johnwargo
Created November 8, 2016 13:43
Show Gist options
  • Save johnwargo/b586b7187c581cb3a2cb3c2e2c429cb0 to your computer and use it in GitHub Desktop.
Save johnwargo/b586b7187c581cb3a2cb3c2e2c429cb0 to your computer and use it in GitHub Desktop.
Node Command Arguments Parsing
var validArgs = ['some_command', 'another_command'];
//=================================================================
//First lets sort out the command line arguments
//=================================================================
var userArgs;
//Is the first item 'node'? then we're testing
if (process.argv[0].toLowerCase() == 'node') {
//whack the first two items off of the list of arguments
//This removes the node entry as well as the module name entry (the
//program we're running)
userArgs = process.argv.slice(2);
} else {
//whack the first item off of the list of arguments
//This removes just the module name entry
userArgs = process.argv.slice(1);
}
//now parse the command line options
var numArgs = userArgs.length;
if (numArgs > 0) {
//Get the first parameter all lowercase
var arg1 = userArgs[0];
if (validArgs.indexOf(arg1) > -1) {
//Then we have one of our valid commands
doLog("We have a valid argument");
switch (arg1) {
case '-ls':
//List the ics files we have in the home directory
listICSFiles();
break;
case '-prepare':
if (numArgs > 1) {
//Take the specified file path and process the file
prepareICSFile(userArgs[1]);
} else {
//Missing argument (need a file path)
console.log("\nMissing command-line argument. Need file path when -prepare option is used\n".error);
displayHelp();
}
break;
}
} else {
doLog("Detected an invalid parameter, so we must have a file path");
//Not in the array, so must be a file path
//validate that we have a file and it exists
//if so, process it!
processICSFile(arg1);
}
} else {
//Missing command line oarguments
console.log("\nMissing command-line arguments\n".error);
displayHelp();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment