我如何将命名参数传递给phantomjs文件

How can I pass named arguments to phantomjs file

本文关键字:参数传递 phantomjs 文件      更新时间:2023-09-26

我们可以将未命名的参数传递给phantomjs,并编写以下代码来控制台记录所有参数。

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);
  });
}

因此,如果我们使用phantomjs index.js 1 2 3运行phantomjs文件,控制台将记录:1 2 3

我的问题是如何将命名参数传递给phantomjs文件,以便我可以像下面这样开始我的脚本:

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

您可以通过这种方式读取命名参数(这是非常快速的&肮脏的):

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);
    }
});
输出:

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