How to Use CasperJS in node.js?


I would like to use CasperJS in node.js.

I have referred to the following URL's to use CasperJS in node.js:

With the help of the above URLs I have written the following code:

//DISPLAY=:0 node test2.js
var phantom = require('phantom');
console.log('Hello, world!');
phantom.create(function (ph) {
    ph.casperPath = '/opt/libs/casperjs'
    var casper = require('casper').create();

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

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

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

When I run this code, I got the following error:


tz@tz-ubuntu:/opt/workspaces/TestPhantomjs$ DISPLAY=:0 node test2.js 
Hello, world!
Error: Cannot find module 'casper'
    at Function._resolveFilename (module.js:332:11)
    at Function._load (module.js:279:25)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at /opt/workspaces/TestPhantomjs/test2.js:6:14
    at Object.<anonymous> (/opt/workspaces/TestPhantomjs/node_modules/phantom/phantom.js:82:43)
    at EventEmitter.<anonymous> (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode/index.js:215:30)
    at EventEmitter.emit (events.js:67:17)
    at handleMethods (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode-protocol/index.js:138:14)
    at EventEmitter.handle (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode-protocol/index.js:98:13)
phantom stdout: Unable to load casper environment: Error: Failed to resolve module fs, tried fs
12/26/2012 1:34:54 AM

Accepted Answer

Nicolas Perriault
2012/2/27 天猪 蓝虫. :

I wan to use casperjs in nodejs. and refs to: and

You can't run CasperJS that way; QtWebKit and V8 don't share the same js environment (and event loop), so your node.js app won't be able to load and use a CasperJS module. You have to run your CasperJS script separately using a subprocess call, like this one on github. I don't plan to make CasperJS compatible with phantomjs-node because it uses alert()-based dirty hacks I'm not easy with.

Cheers, -- Nicolas Perriault

7/10/2014 7:13:36 AM

You can use SpookyJS to drive CasperJS from Node.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow