How to pass a variable as an argument to a CasperJS script through the command line?

user1816910 picture user1816910 · Feb 13, 2014 · Viewed 10.5k times · Source

I'm using PhantomJs, CasperJs, and Js in a js file ran through the cmd.

Imagine we had two files(test1.js, and test2.js). Both files have a url/site variable that directs the test to a particular address. Everytime an environment changed or the target location changed, we would need to update this variable.

To avoid having to update the files, I'd like to pass the values through the command line, as to where to test this.

Is there a way to declare the string variable through the cmd as you run the file?

E.g.:

casperjs test.js "var site='http://google.com';"

Answer

kapa picture kapa · Feb 13, 2014

The documentation says you can pass command-line parameters.

CasperJS ships with a built-in command line parser on top of PhantomJS’ one, located in the cli module; it exposes passed arguments as positional ones and named options

But no worries for manipulating the cli module parsing API, a Casper instance always contains a ready to use cli property, allowing easy access of all these parameters.

Example code:

var casper = require("casper").create();

casper.echo("Casper CLI passed args:");
require("utils").dump(casper.cli.args);

casper.echo("Casper CLI passed options:");
require("utils").dump(casper.cli.options);

casper.exit();

Execution results:

$ casperjs test.js arg1 arg2 arg3 --foo=bar --plop anotherarg Casper

CLI passed args: [
    "arg1",
    "arg2",
    "arg3",
    "anotherarg" ]
Casper CLI passed options: {
    "casper-path": "/Users/niko/Sites/casperjs",
    "cli": true,
    "foo": "bar",
    "plop": true }