Skip to main content

How to pass command line arguments to a Node.js app?

1 min read

Older Article

This article was published 8 years ago. Some information may be outdated or no longer applicable.

If you’ve ever launched an application from the command line (Java, C#, C/C++), you know that passing data to it is dead simple: add parameters when you run it. I did a lot of this at university during a Software Engineering degree, many years ago. Here’s how to capture those parameters in Node.js.

Node.js exposes process.argv, an array containing every argument you’ve passed. Here’s a quick example:

const args = process.argv;
args.forEach((arg) => console.log(arg));

Run it and you’ll notice something: the output includes the path to the Node binary and the filename, not just your arguments:

$ node app.js arg1 arg2
/usr/local/bin/node
/path/to/app.js
arg1
arg2

To strip those out and get only the arguments you supplied, slice the array:

const args = process.argv.splice(2);
args.forEach((arg) => console.log(arg));

That gives you just the arguments you actually care about.

In a follow-up article, we’ll look at how to constantly listen for user input.