Last active
January 7, 2017 21:25
-
-
Save ozzieperez/85f5333130b93f8a5a5ec0bda6a170d1 to your computer and use it in GitHub Desktop.
Get Command Line Arguments 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
/* Example: Say you run this from the command line: | |
node myscript.js -color blue -names joe jenny -month september | |
You can get the arguments in your script by calling the following method as such: | |
var color = getCmdLineArgument("-color") //returns "blue" | |
var names = getCmdLineArgument("-names", 2) //returns ["joe", "jenny"] | |
var month = getCmdLineArgument("-month") //returns "september" | |
var ghost = getCmdLineArgument("-ghost") //returns null | |
*/ | |
function getCmdLineArgument(argument, numberOfValues=1){ | |
if(!numberOfValues || typeof(numberOfValues) != "number" || numberOfValues<1){ | |
throw "Invalid number of values"; | |
} | |
if(argument == null){ | |
throw "Invalid argument" | |
} | |
var argIndex = process.argv.indexOf(argument); | |
if(argIndex == -1){ | |
return null; | |
} | |
if(argIndex + numberOfValues > process.argv.length-1){ | |
throw "Number of values expected exceeds array size" | |
} | |
if(numberOfValues == 1){ | |
return process.argv[argIndex+numberOfValues]; | |
} else { | |
return process.argv.slice(argIndex+1, argIndex+numberOfValues+1); | |
} | |
} | |
/* | |
Returns true if the argument was passed in from the command line. | |
Example: | |
From command line: | |
node myscript.js --help | |
In our script.js: | |
var wantsHelp = hasCmdLineArgument("--help"); // returns true; | |
*/ | |
function hasCmdLineArgument(argument){ | |
return process.argv.indexOf(argument) != -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment