nodejs

Parsing command line arguments with Node.js

Basic parsing of command line arguments is pretty simple with Node.js. It exposes an array process.argv that arguments can be read from.

If you save the line below to a file, it will output all of the arguments that were passed when calling it with node:

console.log(process.argv);

Let's try calling it:

$ node /tmp/args.js hello world
[ '/usr/bin/node', '/tmp/args.js', 'hello', 'world' ]

You'll notice that the first two items in the array are the node binary and the path to the file. That's because those are still considered arguments to the shell. It's common to just slice those off.

const args = process.argv.slice(2);

Functionality like parsing flags isn't supported out of the box, but there are plenty of libraries to help out with that.

more Node.js posts

more JavaScript posts