[ Solved – 10 Answers ] JAVASCRIPT – How to pass command line arguments
Table Of Content
- Here running node like this
- This will generate
- This returns
- Inspired by UNIX getopt utility, it is as trivial as follows
- If you run the previous code with this command
- Then ops object will be as follows
- So you can use it as you want. For instance
- If we call ops.printHelp() we will get the following
- You can install stdio module using NPM
- Then your script is written as follows
- file: parse-cli-arguments.js
- Than just do
- If we want to run something like this
- Or something like
- We have a web server written in Node.js that we would like to launch with a specific folder. Does not sure how to access arguments in JavaScript.
Here running node like this:
[ad type=”banner”]Where server.js is the code.
$ node -h
Usage: node [options] script.js [arguments]
How to access those arguments in JavaScript?
The arguments are stored in process.argv
process.argv is an array containing the command line arguments. The first element will be ‘node’, the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.
This will generate:
- To normalize the arguments like a regular javascript function would receive, we do this in my node.js shell scripts:
Note : The first arg is usually the path to nodejs, and the second arg is the location of the script you’re executing.
- To use the minimist library. We can use node-optimist but it has since been deprecated.
Here is an example of how to use it taken straight from the minimist documentation:
- Vanilla javascript argument parsing:
This returns:
- This is very similar to how bash scripts access argument values.
- Stdio Library
- The easiest way to parse command-line arguments in NodeJS is using the stdio module.
Inspired by UNIX getopt utility, it is as trivial as follows:
[ad type=”banner”]
If you run the previous code with this command:
Then ops object will be as follows:
So you can use it as you want. For instance:
Grouped options are also supported, so you can write -om instead of -o -m.
Furthermore, stdio can generate a help/usage output automatically.
If we call ops.printHelp() we will get the following:
[ad type=”banner”]
The previous message is shown also if a mandatory option is not given (preceded by the error message) or if it is mispecified (for instance, if you specify a single arg for an option and it needs 2).
You can install stdio module using NPM:
-
If your script is myScript.js and you want to pass the first and last name, ‘Wiki Techy’, as arguments like below:
Then your script is written as follows:
- Here is an another solution:
Output is here (it reads options with dashes etc, short and long, numeric etc).
-
we can parse all arguments and check if they exist.
file: parse-cli-arguments.js:
Than just do:
- npm install ps-grab

