Reputation: 183
I am using CasperJS to test a website. A part of the test is resource check.
What I want to do:
Pass array or object array to CasperJS and iterate through them. The first step is one array then object array. both have same issue.
Node.js code:
require('child_process').exec('/usr/local/bin/casperjs script.js [url,regex]' , function(err, stdout, stderr) {
err && console.log(err);
stderr && console.log(stderr.toString());
stdout && console.log(stdout.toString());
})
Casperjs script:
var casper = require('casper').create(),
a = casper.cli.args[0],
// we need something here to string to js array
w=a[0],
r=a[1];
casper.start(w, function() {
if (this.resourceExists(r)) {
console.log("PASS\t" +r+ "\t"+ w);
} else {
console.log("FAIL\t" +r+ "\t"+ w);
}
});
casper.run();
The problem is CasperJS takes args as string.
Upvotes: 0
Views: 1040
Reputation: 183
Better approach to problem: https://groups.google.com/forum/#!topic/casperjs/bhA81OyHA7s
Passing variables as options. Works like a charm
My Final nodejs:
var exec = require('child_process'),
array = [
{url:"",regex:""}
];
for (var i = 0; i < array.length; i++) {
var url = array[i]["url"];
var regex = array[i]["regex"];
exec.exec('/usr/local/bin/casperjs casper2.js --url="'+url+'" --regex="'+regex+'" ' , function(err, stdout, stderr) {
err && console.log(err);
stderr && console.log(stderr.toString());
stdout && console.log(stdout.toString());
});
};
In CasperJS
w=casper.cli.get("url"),
reg= casper.cli.get("regex"),
rpart = reg.split("/"),
r=new RegExp(rpart[1],rpart[2]);
casper.start(w, function() {
if (this.resourceExists(r)) {
console.log("PASS\t" +r+ "\t"+ w);
} else {
console.log("FAIL\t" +r+ "\t"+ w);
}
});
casper.run();
Upvotes: 0
Reputation: 61952
When you call it like that:
'/usr/local/bin/casperjs script.js "[\''+yourURL+'\',\''+yourRegex+'\']"'
You could simply use
a = JSON.parse(casper.cli.args[0]),
w = a[0],
r = new RegExp(a[1]);
If casper.cli.args[0]
is actually JSON, then it can be parsed as such. resourceExists()
takes regular expressions only as RegExp
objects.
A better way if the data that you pass gets too long, then you should write the data to a temporary file with node.js' fs module and read it with PhantomJS' fs module, parsing it along the way.
Upvotes: 1