If you’ve worked on a Node.js command-line program, you were probably faced with the extraction of command line arguments. Node.js provides all command line arguments in the
process.argv array. However, the contents of the array aren’t what you might expect.
What’s in process.argv?
The first two items in
So the first command line argument is the third item in the array. For example, consider the following command that runs a Node.js program:
node index.js --watch
The contents of
process.argv will look something like this (depending on your system and file root)
While the first two items in the array might be useful to some, chances are that you’re only interested in
Using destructuring to extract arguments
process.argv array into pieces and only use what you need. For example, this code separates the array into its three parts:
const [ bin, sourcePath, ...args ] = process.argv; console.log(args); // "--watch"
bin variable receives the Node.js executable path,
args is an array containing all of the remaining command line arguments.
You can take this one step further and just omit
sourcePath if you have no use for them:
const [ , , ...args ] = process.argv; console.log(args); // "--watch"
The two commas at the beginning of the pattern indicate that you’d like to skip over the first two items in the array and store the remaining items in the
args array. You can then further process
args to determine what to do next.