I've retroactively made this article covering very basic Mocha/Chai/Sinon testing the Part 1 of this series. Let's jump right into Part 2, which is...
In several takehome challenges, I've been asked to create an application that accepts one or more arguments from the command-line. Typically, they've involved passing a filename, or a date formatted in a specific format like YYYY-MM-DD.
Let's look at the Node.js documentation for
process.argv, a property allowing us to access command-line arguments:
process.argvproperty returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be
process.argv0if access to the original value of
process.argv is an array containing strings of the command-line arguments used to the run the code. Let's run
$ node app.js and
console.log(process.argv) to see what we get:
$ node app.js [ '/Users/isalevine/.nvm/versions/node/v11.10.0/bin/node', '/Users/isalevine/coding/nodejs/csv-parse-practice/app.js' ]
process.argv shows the path to Node.js, and
process.argv shows the path to the
app.js file we ran. Both are accessible as strings.
Now lets add an extra argument, like the filename of a local .csv file:
$ node app.js example_data.csv [ '/Users/isalevine/.nvm/versions/node/v11.10.0/bin/node', '/Users/isalevine/coding/nodejs/csv-parse-practice/app.js', 'example_data.csv' ]
We have a new string in our array:
process.argv is the filename we supplied. You can continue to add as many arguments as you want!
$ node app.js example_data.csv 2019-01-01 and_so_on and_so_on_again and_so_on_some_more [ '/Users/isalevine/.nvm/versions/node/v11.10.0/bin/node', '/Users/isalevine/coding/nodejs/csv-parse-practice/app.js', 'example_data.csv', '2019-01-01', 'and_so_on', 'and_so_on_again', 'and_so_on_some_more' ]
Another great thing about using
process.argv is that the
process object, and its properties and contents (such as
.argv) are available as soon as your code runs, and is accessible globally. Again, from the Node.js docs:
processobject is a
globalthat provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using
So convenient! Now go forth and wreak command-line-argument-passing havoc!
And while you're here, feel free to leave a comment expanding on
process or Node.js command-line arguments--we've only scratched the surface!