Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 694 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I pass command line arguments to a Node.js program?

#11
There's an app for that. Well, module. Well, more than one, probably hundreds.

[Yargs][1] is one of the fun ones, its docs are cool to read.

Here's an example from the github/npm page:

#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);

Output is here (it reads options with dashes etc, short and long, numeric etc).

$ ./nonopt.js -x 6.82 -y 3.35 rum
(6.82,3.35)
[ 'rum' ]
$ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
(0.54,1.12)
[ 'me hearties', 'yo', 'ho' ]


[1]:

[To see links please register here]

Reply

#12
A simple snippet if any need it:

var fs = require('fs'), objMod = {};

process.argv.slice(2).map(function(y, i) {
y = y.split('=');
if (y[0] && y[1]) objMod[y[0]] = y[1];
else console.log('Error in argument number ' + (i+1));
});

Reply

#13
Optimist (node-optimist)
====

Check out [optimist library](

[To see links please register here]

), it is much better than parsing command line options by hand.

**Update**

Optimist is deprecated. Try [yargs](

[To see links please register here]

) which is an active fork of optimist.
Reply

#14
<h1>Without libraries</h1>

If you want to do this in vanilla JS/ES6 you can use the following solution

worked only in **NodeJS > 6**

const args = process.argv
.slice(2)
.map((val, i)=>{
let object = {};
let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
if(!prop){
object[val] = true;
return object;
} else {
object[prop[1]] = value[1] ;
return object
}
})
.reduce((obj, item) => {
let prop = Object.keys(item)[0];
obj[prop] = item[prop];
return obj;
}, {});

And this command

node index.js host=http://google.com port=8080 production

will produce the following result

console.log(args);//{ host:'http://google.com',port:'8080',production:true }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true






p.s. Please correct the code in map and reduce function
if you find more elegant solution, thanks ;)





Reply

#15
whithout librairies: using Array.prototype.reduce()
===
const args = process.argv.slice(2).reduce((acc, arg) => {

let [k, v = true] = arg.split('=')
acc[k] = v
return acc

}, {})

for this command ```node index.js count=2 print debug=false msg=hi```

console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }

also,
--
we can change

let [k, v = true] = arg.split('=')
acc[k] = v
by (much longer)

let [k, v] = arg.split('=')
acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v
to auto parse Boolean & Number

console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
Reply

#16
[command-line-args](

[To see links please register here]

) is worth a look!

You can set options using the main notation standards ([learn more](

[To see links please register here]

)). These commands are all equivalent, setting the same values:

$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js

To access the values, first create a list of [option definitions](

[To see links please register here]

) describing the options your application accepts. The [`type`](

[To see links please register here]

) property is a setter function (the value supplied is passed through this), giving you full control over the value received.

const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'src', type: String, multiple: true, defaultOption: true },
{ name: 'timeout', alias: 't', type: Number }
]

Next, parse the options using [commandLineArgs()](

[To see links please register here]

):

const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)

`options` now looks like this:

{
src: [
'one.js',
'two.js'
],
verbose: true,
timeout: 1000
}

### Advanced usage

Beside the above typical usage, you can configure command-line-args to accept more advanced syntax forms.

[Command-based syntax](

[To see links please register here]

) (git style) in the form:

$ executable <command> [options]

For example.

$ git commit --squash -m "This is my commit message"

[Command and sub-command syntax](

[To see links please register here]

) (docker style) in the form:

$ executable <command> [options] <sub-command> [options]

For example.

$ docker run --detached --image centos bash -c yum install -y httpd

## Usage guide generation

A usage guide (typically printed when `--help` is set) can be generated using [command-line-usage](

[To see links please register here]

). See the examples below and [read the documentation](

[To see links please register here]

) for instructions how to create them.

A typical usage guide example.

![usage](

[To see links please register here]

)

The [polymer-cli](

[To see links please register here]

) usage guide is a good real-life example.

![usage](

[To see links please register here]

)

## Further Reading

There is plenty more to learn, please see [the wiki](

[To see links please register here]

) for examples and documentation.
Reply

#17
as stated in the node docs
The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.

For example, assuming the following script for process-args.js:

// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});

Launching the Node.js process as:

$ node process-args.js one two=three four

Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
Reply

#18
Most of the people have given good answers. I would also like to contribute something here. I am providing the answer using `lodash` library to iterate through all command line arguments we pass while starting the app:

// Lodash library
const _ = require('lodash');

// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
_.map(process.argv, (arg) => {
console.log(arg);
});
};

// Calling the function.
runApp();
To run above code just run following commands:

npm install
node index.js xyz abc 123 456
The result will be:

xyz
abc
123
456
Reply

#19
The simplest way of retrieving arguments in Node.js is via the process.argv array. This is a global object that you can use without importing any additional libraries to use it. You simply need to pass arguments to a Node.js application, just like we showed earlier, and these arguments can be accessed within the application via the process.argv array.

The first element of the process.argv array will always be a file system path pointing to the node executable. The second element is the name of the JavaScript file that is being executed. And the third element is the first argument that was actually passed by the user.

'use strict';

for (let j = 0; j < process.argv.length; j++) {
console.log(j + ' -> ' + (process.argv[j]));
}

All this script does is loop through the process.argv array and prints the indexes, along with the elements stored in those indexes. It's very useful for debugging if you ever question what arguments you're receiving, and in what order.

You can also use libraries like yargs for working with commnadline arguments.
Reply

#20
`process.argv` is your friend, capturing command line args is natively supported in Node JS. See example below::

process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
})
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through