Simple Options Parser for PhantomJS

18. November 2011 14:33 by Cameron in javascript, PhantomJS, Programming  //  Tags: , , ,   //   Comments

Recently I needed a way to parse command line options with PhantomJS. I didn't see anything else on the web that allowed for abitrary ordering of command line arguments to PhantomJS scripts so I made my own. Here's the code for those interested:

// argument results
var a1, a2, a3, a4;

function optionParser() {	
	var opt = 0;
	while((opt < phantom.args.length) && (phantom.args[opt][0]=='-')) {
		var sw = phantom.args[opt];
		switch(sw) {
			case '-a1':
				opt++;
				a1 = phantom.args[opt];
				break;
			case '-a2':
				opt++;
				a2 = phantom.args[opt];
				break;
			case '-a3':
				opt++;
				a3 = phantom.args[opt];
				break;
			case '-a4':
				opt++;
				a4 = phantom.args[opt];
				break;
			default:
				console.log('Unknown switch: ' + phantom.args[opt]);
				phantom.exit();
				break;
		}
		opt++;
	}
}

This can easily be modified to work with an array of argument results or you can simply read in each argument into its own variable. Also, you can read in integers and in your application logic, use isNaN() to check if the input is a valid integer.

blog comments powered by Disqus

Month List

Tag cloud