使用casperjs中的节点模块
是否可以安装通过npm安装的节点模块,然后从casperjs脚本中获取?
(我看到很多post和工具,用于在node.js中运行casper或phantom,但这不是我想要做的。)
casperjs文档似乎说这是可能的,但只能用手写的玩具模块来展示,而这些模块并不真正做任何事情。 我试图安装的真实世界的模块是imap
,但在这一点上,我不能得到任何模块的工作,即使内置的net
。 简单的例子:
npm install imap echo "var test = require('imap');" > test.js casperjs test.js
给我:
CasperError: Can't find module imap /usr/local/src/casperjs/bin/bootstrap.js:263 in patchedRequire test.js:1
(我可以从npm ls
看到imap模块,我可以从node.js脚本中使用它)。
或者使用内置模块:
echo "var test = require('net');" > test.js casperjs test.js
抱怨“找不到模块网”
我有npm --version
1.4.14和nodejs --version
v0.10.29。 那些太旧了,我想知道? (Casper是1.1.0-beta,Phantom是1.9.7,两者都是最新版本。)
PhantomJS和SlimerJS(用于CasperJS的引擎)不是Node.js模块。 为方便起见,可以通过npm进行安装。 他们有不同于Node.js的模块的基础架构。
您将无法使用imap
或任何依赖于net
模块的模块。 正如Fanch所指出的那样,有些模块可以在phantomjs运行库中工作。
如果一个模块只使用某些本地node.js模块的某些function,则可以尝试更改实现以使用phantomjs提供的API。 我不认为这很容易。 大多数时候你会碰壁。
在imap
的情况下,这是相当无望的。 你甚至不能重新实现require("net").Socket
,因为Phantomjs不支持WebSocket(至less在1.9.7中)。
这里有一个颜色模块的例子:
var colors = require('colors'); casper.test.begin('\n*Colors module*\n', function suite(test) { casper.start() .thenOpen('https://www.google.fr/', function() { console.log("test require\n".zebra); console.log("test require\n".rainbow); console.log("test require\n".red.underline.bold); }) .run(function() { test.done(); }); });
- 节点模块
- 颜色
- testnode.js
casperjs test testnode.js
输出:
当所需模块具有依赖关系时,似乎并不那么简单。
在我的情况下,我想加载underscorejs。 下划线是一系列函数,并没有与javascript对象的复杂交互,所以没有问题只需要JavaScript文件,然后访问其function。
我从find根节点到我的nodejs安装(从CLI)开始:
node --help
这导致我find我的节点path:
echo $NODE_PATH
当时是:
/usr/local/lib/node_modules/
下划线在
/usr/local/lib/node_modules/underscore/underscore.js
所以我在CasperJS脚本中的最终需求声明是。
var _ = require('/usr/local/lib/node_modules/underscore/underscore.js');
现在在我的脚本中,我testing是否加载了underscorejs:
this.echo(_.now());
我看到目前的时间。
CAVEAT:因为这是asynchronous运行的,所以如果你把_.now()语句放在require之后,它会给你一个未定义的对象错误。 注意,我使用的是Casper 1.1,它使用PhantomJS的本地require()函数。 如果你正在使用<卡斯帕1.1,我不认为要求将工作。
更新:既然是这样,我使用CasperJS然后()函数同步加载我的工具,确保在全局范围内声明我的variables。 这是看起来如何:
//at the top of the file-ish, declare variables that will hold loaded libraries. var utils, _; var casper = require('casper').create(); //create casper casper.start('http://example.com'); //start casper at URL. casper.then(function loadRequires(){ //load the requirements utils = require('utils', function(){this.echo('utils loded')}); _ = require('/usr/local/lib/node_modules/underscore/underscore.js'); }); casper.then(function myAwesomeStuff() { this.echo(_.now()); //now, access the loaded requirements utils.dump('this stuff is soooo awesome!!!!!!!!!!!!!!!!!!!!'); //do stuff on the page you opened in the start function here. ); });
您可以在API文档中阅读关于Casper原型和then()方法的更多信息: http : //casperjs.readthedocs.org/en/latest/modules/casper.html#casper-prototype