Darren Cook Darren Cook - 8 months ago 389
Node.js Question

Use a node module from casperjs

Is it possible to install a node module, installed via npm, and then

it from a casperjs script?

(I see lots of posts and tools for running casper or phantom from inside node.js, but that is not what I'm trying to do.)

The casperjs docs seem to say it is possible, but only show with hand-written toy modules that don't really do anything. The real-world module I'm trying to install is
, but at this point I cannot get any module to work, even built-in ones like
. Simple example:

npm install imap
echo "var test = require('imap');" > test.js
casperjs test.js

Gives me:

CasperError: Can't find module imap

/usr/local/src/casperjs/bin/bootstrap.js:263 in patchedRequire

(I can see the imap module from
npm ls
, and I can use it fine from a node.js script.)

Or alternatively with a built-in module:

echo "var test = require('net');" > test.js
casperjs test.js

Complains "Can't find module net"

I have
npm --version
of 1.4.14 and
nodejs --version
of v0.10.29. Are either of those too old, I wonder? (Casper is 1.1.0-beta, and Phantom is 1.9.7, both of which are the latest versions.)


PhantomJS and SlimerJS (the engines that are used for CasperJS) are not Node.js modules. They can be installed through npm for convenience. They have a different base infrastructure of modules which is distinct from Node.js.

You will not be able to use imap or any module that depends on the net module. As Fanch points out, there are modules that can work inside the phantomjs runtime.

If a module only uses some functionality of some native node.js module, you could try to change the implementation to use the API that phantomjs provides. I don't think this is easy though. Most of the time you will run into a wall.

In the case of imap, it is pretty hopeless. You cannot even re-implement the require("net").Socket, because WebSockets are not supported in phantomjs (at least in 1.9.7).