Handling Command Line Arguments in Node
When running a script in a programming language, you have the ability to pass along command line arguments (which can change the functionality of the script upon each run). In node, we can access command line arguments through process.argv
, which is an array:
console.log(process.argv);
/*
[
'/Users/drew/.nvm/versions/node/v18.16.0/bin/node',
'/Users/drew/Dev/getThere/src/scraper/scraper.js'
]
*/
The the 0th
element is the node interpreter and the 1st
element is the name of the script. From the 2nd
element on, we can grab command line arguments we pass. For instance, say we run node ./scraper.js fakeCommandLineArgument
.
console.log(process.argv);
/*
[
'/Users/drew/.nvm/versions/node/v18.16.0/bin/node',
'/Users/drew/Dev/getThere/src/scraper/scraper.js',
'fakeCommandLineArgument'
]
*/
We can then grab our command line argument with process.argv[2]
. But, this isn’t ideal since the position matters. It would be better if we could pass command line arguments in a manner we’re used to in the CLI like so: node ./scraper.js --sourceCity=SFO
. We can manually write some functions to parse out the arguments and give them back to use, but there’s already a nice library called commander that does that for us. So, let’s use that.
const { program } = require("commander");
program
.option("-s, --sourceCity <city>", "City to start from")
.option("-d, --destinationCity <city>", "City to end in");
program.parse();
console.log(program.opts());
// { sourceCity: "SFO", destinationCity: "JFK" }
Now if we run node ./scraper.js --sourceCity=SFO --destinationCity=JFK
, we’ll get back { sourceCity: "SFO", destinationCity: "JFK" }
in program.opts()
. Sweet.
If we want to make these required, thus throwing an error if they are not present, we can use requiredOption
:
const { program } = require("commander");
program
.requiredOption("-s, --sourceCity <city>", "City to start from")
.requiredOption("-d, --destinationCity <city>", "City to end in");
program.parse();
console.log(program.opts());
If we were to run this without either the sourceCity
or the destinationCity
, an error would be thrown:
error: required option '-s, --sourceCity <city>' not specified
Accepting command line arguments can make your scripts more flexible and usable. If you’re using them, throw in commander to provide command line argument parsing and basic presence validation so you can move forward on solving awesome problems instead of manually parsing out command line arguments.