The Grouparoo Blog
Last week when working on Grouparoo's OneSignal integration, I wrote a quick CLI script to create users in their system that we could use for testing. This script would take in a single argument, which would be the
external_user_id on OneSignal:
$ ./create_user <external_user_id>
To allow parsing command-line arguments, Node provides
process.argv. This property returns an array that contains all arguments passed when the process was launched. The first two arguments are always the path to node and the path to the JS file being executed, respectively. For instance, the previous example would return the following array:
// process.argv ["/path/to/node", "/path/to/create_user", "<external_user_id>"];
const [nodePath, scriptPath, externalUserId, ...otherArgs] = process.argv; // Do something with the externalUserId createUser(externalUserId);
Taking a closer look at the example above, you'll notice that we're not actually doing anything with the first two variables.
A common practice is to prefix the unused variables with an underscore to clearly indicate that they will not be used:
const [_nodePath, _scriptPath, externalUserId] = process.argv;
Something very similar to this is what I have usually done in the past, but I was writing this script pretty quickly and (accidentally) omitted the variable names, writing this instead:
const [, , externalUserId] = process.argv;
Much to my surprise, when I saved the file Prettier came in and formatted it without any complaints. It turns out you don't even need to assign the unused variables!
This works anywhere in the array, so you can also do this with elements in the middle:
// Only assign the first and fourth elements const [one, , , four] = ["one", "two", "three", "four"];
It's great to learn something new about things you use so frequently!
Tagged in Engineering Notes
See all of Pedro S Lopez's posts.
Pedro is a full-stack Software Engineer working on Grouparoo, an open source data framework that easily connects your data to business tools. He's a tinkerer that enjoys reverse engineering, automation and technology in general. When he's not programming, Pedro spends his time playing and listening to music.
Learn more about Pedro @ https://pedroslopez.me/
Stay up to date
We will let you know about our launch and new content.
Share this post