Something new I learned this week was about how arguments are passed into Node programs from the command line. This was a principle I learned a lot about in a coding challenge I did a while back, but in several other languages. Being more familiar with JavaScript, and having already learned how to do it in a few different (but similar) ways, I was able to pick it up pretty easily.

All you need, in order to use command line arguments in Node, is process.argv. That is an array, and it’s really important to remember that the first 2 elements will have nothing to do with your elements! They actually can differ/depend on your machine, and where the file is located on your hard drive. They can be useful in certain contexts, but when we talk about CLI arguments, we are talking about every element that comes after those 2. Often, you can call process.argv.shift() twice, to get rid of those, and you’re left with just an array of elements in process.argv. Then you can do as you please with those arguments within the program!

This sort of thing is very helpful because it allows you to dynamically give values to the program without having to save them into any files anywhere. You simply state the values when you execute the program. If you have a long list of arguments you want to supply, it of course makes sense to include those in a file or database, which is then supplied as an argument, or hard-coded for the program to reference specifically – but that’s a discussion for another day! I’m still in early stages of learning node, and I am ultimately focused on using it in the context of web server functionality. This is just a neat thing I learned, that may come in handy sometime!