带有MongoDB NPM模块的CasperJS

我正在运行CasperJS 1.1.0-DEV,并要求mongoskin NPM模块将文档插入到Mongodb中。

但是使用mongoskin NPM模块

 var mongo = require('mongoskin') var db = mongo.db('mongodb://localhost:27017/test', {native_parser: true})') 

抛出错误

 ReferenceError: Can't find variable: process /Users/username/casper-test/node_modules/mongoskin/index.js:1 /Users/username/casper-test/node_modules/mongoskin/index.js:2 TypeError: 'undefined' is not a function (evaluating 'mongo.db('mongodb://localhost:27017/test', {native_parser: true})') test.js:3 

应该如何正确的使用CasperJS和mongoskin这样的NPM模块?

CasperJSbuild立在PhantomJS之上,它本身与node.js有不同的执行环境。 CasperJS可以使用与node.js类似的模块基础结构,但大多数节点模块不能直接在CasperJS中运行。 由于PhantomJS不提供相同的基本模块,因此不能使用使用它们的模块。 它可能不会重写mongoskin使用PhantomJS模块。

另一种方法是编写一个使用mongoskin的node.js脚本,然后通过child_process模块使用该脚本调用节点。 您需要将其与CasperJS中的控制stream同步,以便您可以使用casper.waitFor()

 var execFile = require("child_process").execFile; casper.callMongoskin = function(then, onTimeout, timeout){ var finished = false; var results; execFile("node", ["mongoskin_script.js"], null, function (err, stdout, stderr) { console.log("execFileSTDOUT:", JSON.stringify(stdout)); console.log("execFileSTDERR:", JSON.stringify(stderr)); results = {stuff: "..."}; finished = true; }); this.waitFor(function(){ return finished; }, function _then(){ if (typeof then === "function") { then.call(this, results); } }, onTimeout, timeout); }; casper.thenCallMongoskin = function(then, onTimeout, timeout){ return this.then(function(){ this.callMongoskin(then, onTimeout, timeout); }); }; 

我会让你弄清楚你想传递什么。下面是你将如何使用它:

 casper.start(url).thenCallMongoskin(function(results){ require('utils').dump(results); }).run();