使用没有ES6语法和良率的Nightmare.js
我使用nightmare.js构build了一个简单的节点脚本来抓取网站
var Nightmare = require('nightmare'); var vo = require('vo'); vo(run)(function(err, result) { if (err) throw err; }); function *run() { var x = Date.now(); var nightmare = Nightmare(); var html = yield nightmare .goto('http://google.com') .evaluate(function() { return document.getElementsByTagName('html')[0].innerHTML; }); console.log("done in " + (Date.now()-x) + "ms"); console.log("result", html); yield nightmare.end(); }
我想在一个使用较旧版本的节点的环境中运行这个不支持ES6function的节点。 在github页面上没有关于如何做这个没有“yield”关键字的例子。
我在这里find了一个没有使用ES6语法的用法示例: 带有噩梦的网页浏览
我是这样写的:
var night = new Nightmare() .goto('http://www.google.com') .evaluate(function () { return document.getElementsByTagName('html')[0].innerHTML; },function (html) { console.log("result", html); } ) .run(function (err, nightmare) { if (err) return console.log(err); console.log('Done!'); });
它不会崩溃,但结果日志loggingfunction永远不会被调用。
使用yield语法, 从“evaluate”获取返回的值是非常简单的 ,但是没有它,我没有find任何方法来做到这一点。
更新写这感谢接受的答案和它的意见。 它使用'Q'并且在0.12之前的节点版本中工作:
var Nightmare = require('nightmare'); var Promise = require('q').Promise; var x = Date.now(); var nightmare = Nightmare(); Promise.resolve(nightmare .goto('http://google.com') .evaluate(function() { return document.getElementsByTagName('html')[0].innerHTML; })).then(function(html) { console.log("done in " + (Date.now()-x) + "ms"); console.log("result", html); return nightmare.end(); }).then(function(result) { }, function(err) { console.error(err); // notice that `throw`ing in here doesn't work });
文件是可怕的,但似乎是梦魇的基础上的贱民。 在callback界面上我没有find太多的信息,但是这样会导致缩进金字塔。
所以最好的办法是使用promise,只要select任何大致遵循ES6标准的库 (它们都可以在非ES6环境中使用)。
您可以轻松地将您的线性发生器代码转换为承诺链, then
通过then
调用取代每个yield
:
var Nightmare = require('nightmare'); var Promise = require('…'); var x = Date.now(); var nightmare = Nightmare(); Promise.resolve(nightmare .goto('http://google.com') .evaluate(function() { return document.getElementsByTagName('html')[0].innerHTML; })).then(function(html) { console.log("done in " + (Date.now()-x) + "ms"); console.log("result", html); return nightmare.end(); }).then(function(result) { … }, function(err) { console.error(err); // notice that `throw`ing in here doesn't work });
- 分段错误(核心转储),通过产生的方式从NodeJS调用python脚本
- 为什么我通过spawn()挂起创build的Nodesubprocess?
- 错误:使用非root用户使用Node.js child_process时,在errnoException(child_process.j2:980:11)处产生ENOENT
- Blender命令行的Node.js产生?
- Nodejs如何等待subprocess退出或允许响应
- 为什么nodejs产生的进程变成<defunct>直到父进程退出
- 节点:按顺序产生进程,inheritancestdio
- sshpass命令在node.js中不起作用
- 节点:追加输出到现有的文件