Feng Yu
Feng Yu

Reputation: 369

How can I pass named arguments to phantomjs file

We can pass unnamed arguments to phantomjs and write the following code to console log all arguments.

var system = require('system');
var args = system.args;

if (args.length === 1) {
  console.log('Try to pass some arguments when invoking this script!');
} else {
  args.forEach(function(arg, i) {
    console.log(i + ': ' + arg);
  });
}

So if we run phantomjs file using phantomjs index.js 1 2 3, the console will log: 1 2 3.

My question is how can I pass named arguments to phantomjs file so that I can start my script like:

>phantomjs index.js --username=user1 --password=pwd

Upvotes: 2

Views: 769

Answers (1)

Ryan Doherty
Ryan Doherty

Reputation: 38740

You can read named arguments this way (this is very quick & dirty):

var system = require('system');
var args = system.args;

args.forEach(function(arg, i) {

    var argValue = arg.split('=');

    if(argValue.length == 2) {
        var arg = argValue[0].replace('--', ''),
            value = argValue[1];

        console.log(arg + ": " + value);
    } else {
        //Handles unnamed args
        console.log(arg);
    }
});

Output:

% phantomjs args.js --foo=bar                                  
args.js
foo: bar

Upvotes: 3

Related Questions