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

标签 javascript phantomjs

我们可以将未命名的参数传递给 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

关于javascript - 如何将命名参数传递给 phantomjs 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39944308/

相关文章:

javascript - 从评估()中处理提交的响应

python - Selenium 驱动程序有时不会点击元素

javascript - 在 ES2015 中,如何以正确的顺序重建带标签的模板文字?

javascript - 简化分页页面列表的生成

javascript - 未在用户电子邮件中收到确认码

javascript - Phantomjs/Casperjs 现在不工作网站检测机器人

jasmine - PhantomJS 在 TeamCity 中抛出 "Unable to access network"

javascript - 三元运算符、if-else 或逻辑 OR 在 javascript 中更快吗?

javascript - 使用 new window[] 创建静态内部函数对象

node.js - 将 phantomJS 部署到 node.js 应用程序?