LoginSignup
10
9

More than 5 years have passed since last update.

CasperJSの導入時、Error: Cannot find module 'casper'が出てプログラムが実行できなかった時の対処法

Last updated at Posted at 2015-07-23

発生時の状況

ちょっとPhantomJSに興味が出たのでCasperJSと一緒に導入してみた

WindowsからPhantomJS,CasperJSをインストールし、test.jsという名前でGooleのキャプチャを取ってくるプログラムを作成。

test.js
var casper = require('casper').create();

casper.start('http://google.com/', function(){
    this.capture('google.png');

});

casper.run();

を 

$ phantomjs test.js
で実行したところ

Error: Cannot find module 'casper'

"casper"が見つからないらしい…

今度はOSをUbuntuに変えてやってみたがまた同じエラー

ちなみにバージョンはPhantomJS 1.9.0,CasperJS 1.1.0-DEVでした

対処

$ casperjs test.js

で実行する。

phantomjsラッパーのcapserjsがインストールしてあるので、わざわざphantomjsからcasperをrequireしなくで直接casperjsから実行すればいい
ということなのだと思われる。

その他の対処法

phantomjsからどうしても呼び出したいときは、casperの場所を明示してあげなきゃいけない(?)らしく、具体的には以下の二行を追加する。

phantom.casperPath = '/path/hoge/casperjsフォルダ';
phantom.injectJs(phantom.casperPath + "/bin/bootstrap.js");

変更後のプログラムはこのようになった

test.js
phantom.casperPath = '/home/genm/programfiles/casperjs';
phantom.injectJs(phantom.casperPath + "/bin/bootstrap.js");

var casper = require('casper').create();

casper.start('http://google.com/', function(){
    this.capture('google.png');

});

casper.run();

これで再度
$ phantomjs test.js

を実行したところちゃんとGoogleのキャプチャを撮ってきてくれた

まとめ

知ってる人にとっては、当たり前なのかもしれないけどJS触ったこともない初心者にはちょっとつらかった。
「Error: Cannot find module 'casper'」で検索かけると日本語ではcoffeescriptで拡張したライブラリ云々のことしかのってなかったので、同じ症状で困っている人の参考になれば良いと思ってる。

10
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9