DEV Community

Omar Dulaimi
Omar Dulaimi

Posted on • Updated on

Natively parse command line args with Nodejs

The 𝗽𝗿𝗼𝗰𝗲𝘀𝘀.𝗮𝗿𝗴𝘃 method lets you natively parse command line arguments, without the need for any additional libraries.

It returns an array of strings containing all the args that were passed when launching the 𝗡𝗼𝗱𝗲𝗷𝘀 process.

The first and second args are reserved, here's what they mean:

First: Is the 𝗽𝗿𝗼𝗰𝗲𝘀𝘀.𝗲𝘅𝗲𝗰𝗣𝗮𝘁𝗵 which is the absolute path of the executable that started the 𝗡𝗼𝗱𝗲𝗷𝘀 process.

Second: Absolute path for the file currently being executed.

Did you learn something new today?

Like and share this post, and follow me for more!

process.argv

Top comments (4)

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Sorry but this is "get" not "parse". Parsing is when you get command line options. When you pass script.js -xo --name=hello and you get that you used option "x" and "o" and "name" with value "hello". You can read what is Parsing on Wikipedia.

I've written NPM package for parsing command line called lily. But there is also well establish one called yargs and it's little friend yargs-parser.

Collapse
 
omardulaimi profile image
Omar Dulaimi

I'm aware of yargs and other parsers. I said parser in this post to note what node does under the hood when it takes the values from the standard input stream; not parsing in the context you're referring to.

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

But this is not something that Node is doing, every single program in the system gets argument as array of strings. So this is by no means parsing by Node. If you will learn C language you will know that arguments in the system are in the form of array of strings. So No Parsing. So your "parsing" is done by the operation system.

Thread Thread
 
omardulaimi profile image
Omar Dulaimi

I think you're right about the string array args. Because argv seems like a convention taken from C and C++. Java havd something similar too. If OS is doing the parsing then that's great, at least it's done somewhere under the hood haha. Thanks for your explanation. I appreciate it.