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

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

In this article, we'll take a look at how to pass command line arguments to a Node.js application executing from the CLI.

Probably there was a time in your life when you executed an application from the command line - typically these would be Java, C# or applications based on C/C++ - I did a lot of these many-many years ago at university as part of a Software Engineering degree. In such situations passing data to the application is trivial - we can add it as keyboard input or launch the application with some parameters. This article focuses on how to capture the parameters.

Node.js is capable of capturing the paramters sent via the CLI. Node.js exposes process.argv which is an array that contains all the arguments that we have passed to the application. Let's take a look at an example:

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

If we check the result, we'll notice that the above returns not only the arguments but also the path of the executed file, plus, the filename itself:

$ node app.js arg1 arg2

If we want to get only the arguments, we need to apply some transformation to the array:

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

The above would only return the arguments that we supply to the terminal.

In a follow up article we'll take a look at how to constantly listen for a user input.


Tamas Piros

Developer Evangelist, experienced Technical Trainer and Google Developer Expert in Web Technologies. Active conference speaker, passionate about the latest & greatest advancements in web technologies.

View Comments
Next Post

Introduction to Serverless (FaaS)

Previous Post

Add Material Design to an Angular application