gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:09:44 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com