Aaron Loften Aaron Loften - 11 months ago 55
Javascript Question

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

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?


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

Answer Source

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:");

casper.echo("Casper CLI passed options:");


Execution results:

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

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