• 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:

jQuery Code
$ node server.js folder
[ad type=”banner”]

Where server.js is the code.

$ node -h
Usage: node [options] script.js [arguments]

How to access those arguments in JavaScript?

jQuery Code
Javjavascript           node.js        arguments              command-line-argumentsascript

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.

jQuery Code
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});

This will generate:

jQuery Code
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four

  • To normalize the arguments like a regular javascript function would receive, we do this in my node.js shell scripts:
jQuery Code
var args = process.argv.slice(2);

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:

jQuery Code
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
jQuery Code
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
jQuery Code
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }

  • Vanilla javascript argument parsing:
jQuery Code
const args = process.argv;
console.log(args);

This returns:

jQuery Code
$ node process-2.js one two=three four
['node', '/Users/dc/node/server.js', 'one', 'two=three', 'four']

  • This is very similar to how bash scripts access argument values.
jQuery Code
$ node yourscript.js banana monkey

var program_name = process.argv[0]; //value will be "node"
var script_path = process.argv[1]; //value will be "yourscript.js"
var first_value = process.argv[2]; //value will be "banana"
var second_value = process.argv[3]; //value will be "monkey"

  • 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:

jQuery Code
var stdio = require('stdio');
var ops = stdio.getopt({
'check': {key: 'c', args: 2, description: 'What this option means'},
'map': {key: 'm', description: 'Another description'},
'kaka': {args: 1, mandatory: true},
'ooo': {key: 'o'}
});

[ad type=”banner”]

If you run the previous code with this command:

jQuery Code
node <your_script.js> -c 23 45 --map -k 23 file1 file2

Then ops object will be as follows:

jQuery Code
{ check: [ '23', '45' ],
args: [ 'file1', 'file2' ],
map: true,
kaka: '23' }

So you can use it as you want. For instance:

jQuery Code
if (ops.kaka && ops.check) {
console.log(ops.kaka + ops.check[0]);
}

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:

jQuery Code
USAGE: node something.js [--check <ARG1> <ARG2>] [--kaka] [--ooo] [--map]
-c, --check <ARG1> <ARG2> What this option means (mandatory)
-k, --kaka (mandatory)
--map Another description
-o, --ooo

[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:

jQuery Code
npm install stdio

  • If your script is myScript.js and you want to pass the first and last name, ‘Wiki Techy’, as arguments like below:
jQuery Code
node myScript.js Wiki Techy

Then your script is written as follows:

jQuery Code
var firstName = process.argv[2]; // Will be set to ‘Wiki'
var lastName = process.argv[3]; // Will be set to ‘Techy'

  • Here is an another solution:
jQuery Code
#!/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).

jQuery Code
$ ./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' ]

  • we can parse all arguments and check if they exist.

file: parse-cli-arguments.js:

jQuery Code
module.exports = function(requiredArguments){
var arguments = {};

for (var index = 0; index < process.argv.length; index++) {
var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
matches = re.exec(process.argv[index]);

if(matches !== null) {
arguments[matches[1]] = matches[2];
}
}
jQuery Code
for (var index = 0; index < requiredArguments.length; index++) {
if (arguments[requiredArguments[index]] === undefined) {
throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
}
}

return arguments;
}

Than just do:

jQuery Code
var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);

  • npm install ps-grab

If we want to run something like this :

jQuery Code
node greeting.js --user Wikitechy --website http://www.wikitechy.com
jQuery Code
var grab=require('ps-grab');
grab('--username') // return ‘Wikitechy'
grab('--action') // return 'http://www.wikitechy.com'

Or something like :

jQuery Code
node vbox.js -OS redhat -VM template-12332 ;
jQuery Code
var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332

Categorized in: