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