Cannot find module 'casper' when invoking through PhantomJS

chitcharonko picture chitcharonko · Sep 10, 2014 · Viewed 10.1k times · Source

I installed PhantomJS in C:\xampp\htdocs\phantom and also I installed CasperJS in this folder C:\xampp\htdocs\casper

When I tried to run these sample code on casper site using phantomjs test.js command:

var casper=require('casper').create();
casper.start('http://google.fr/');

casper.thenEvaluate(function(term) {
    document.querySelector('input[name="q"]').setAttribute('value', term);
    document.querySelector('form[name="f"]').submit();
}, 'CasperJS');

casper.then(function() {
    // Click on 1st result link
    this.click('h3.r a');
});

casper.then(function() {
    console.log('clicked ok, new location is ' + this.getCurrentUrl());
});

casper.run();

It gives me an error telling me that:

Error: Cannot find module 'casper'

What did I do wrong?

Answer

Artjom B. picture Artjom B. · Sep 10, 2014

If you want to run CasperJS through PhantomJS (since you invoke phantomjs test.js) you need some bootstrapping code at the beginning of the script:

phantom.casperPath = 'path/to/node_modules/casperjs';
phantom.injectJs('path/to/node_modules/casperjs/bin/bootstrap.js');

Keep in mind that even on windows, you need to use a forward slash.

If you need the test environment then you also need the line:

phantom.casperTest = true;

Everything is taken from this question: Running 'casperjs test' in phantom

Although this is possible you shouldn't do it. You should invoke CasperJS directly through its executable/batch file in node_modules/casperjs/batchbin.