使用nodeJS和phantomJS来返回networking请求和响应,只能在控制台中工作

我试图复制phantomJS netlog.jsfunction,只在nodeJS。 我正在使用phantomjs-node模块作为桥梁。

通常情况下,这个命令将在phantomjs netlog.js http://www.google.com/ 。 它会返回很多包含所有networking请求和响应的json。

我在这里做的是试图在使用phantomjs-node模块创build的页面内运行netlog.js的代码(忽略phantomjs-node var page = require('webpage').create()

虽然代码不会中断,但我没有得到json的返回。 这里有什么问题? 我是否需要以某种方式pipe理页面请求?

app.js

 var phantom = require('phantom'); siteUrl = "http://www.google.com/" phantom.create(function (ph) { ph.createPage(function (page) { var system = require('system'), address; page.open(siteUrl, function (status) { // console.log("opened " + siteUrl +"\n",status+"\n"); page.evaluate(function () { if (system.args.length === 1) { console.log('Usage: netlog.js <some URL>'); phantom.exit(1); } else { console.log(system.args[1]) address = system.args[1]; page.onResourceRequested = function (req) { console.log('requested: ' + JSON.stringify(req, undefined, 4)); }; page.onResourceReceived = function (res) { console.log('received: ' + JSON.stringify(res, undefined, 4)); }; page.open(address, function (status) { if (status !== 'success') { console.log('FAIL to load the address'); } phantom.exit(); }); } }, function finished(result) { ph.exit(); },thirdLayerLinks); }); }); }, { dnodeOpts: { weak: false } }); 

您在复制粘贴过程中犯了错误。 不应该有一个page.evaluate调用,只有一个page.open调用。 你从基本的phantomjs-node代码中抽取了一点点。

PhantomJS和Node.js有不同的运行时间和极其不同的模块。 没有phantom参考。 另外节点中没有system 。 你可能是指process

然后文档说:

callback不能直接设置,而是使用page.set('callbackName', callback)

固定代码:

 var phantom = require('phantom'); var address = "http://google.com/"; phantom.create(function (ph) { ph.createPage(function (page) { page.set("onResourceRequested", function (req) { console.log('requested: ' + JSON.stringify(req, undefined, 4)); }); page.set("onResourceReceived", function (res) { console.log('received: ' + JSON.stringify(res, undefined, 4)); }); page.open(address, function (status) { if (status !== 'success') { console.log('FAIL to load the address'); } ph.exit(); }); }); }, { dnodeOpts: { weak: false } });