这是传递和选择适用参数的简单方法。非常灵活且易于维护。
像这样使用:
phantomjs tests/script.js --test-id=457 --log-dir=somedir/
或者
phantomjs tests/script.js --log-dir=somedir/ --test-id=457
或者
phantomjs tests/script.js --test-id=457 --log-dir=somedir/
或者
phantomjs tests/script.js --test-id=457
脚本:
var system = require('system');
// process args
var args = system.args;
// these args will be processed
var argsApplicable = ['--test-id', '--log-dir'];
// populated with the valid args provided in availableArgs but like argsValid.test_id
var argsValid = {};
if (args.length === 1) {
console.log('Try to pass some arguments when invoking this script!');
} else {
args.forEach(function(arg, i) {
// skip first arg which is script name
if(i != 0) {
var bits = arg.split('=');
//console.log(i + ': ' + arg);
if(bits.length !=2) {
console.log('Arguement has wrong format: '+arg);
}
if(argsApplicable.indexOf(bits[0]) != -1) {
var argVar = bits[0].replace(/\-/g, '_');
argVar = argVar.replace(/__/, '');
argsValid[argVar] = bits[1];
}
}
});
}
// enable below to test args
//require('utils').dump(argsValid);
//phantom.exit();