-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
92 lines (77 loc) · 1.87 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Module Dependencies
*/
var debug = require('debug')('x-ray:phantom');
var normalize = require('normalizeurl');
var Nightmare = require('nightmare');
var wrapfn = require('wrap-fn');
/**
* Export `driver`
*/
module.exports = driver;
/**
* Initialize the `driver`
* with the following `options`
*
* @param {Object} options
* @param {Function} fn
* @return {Function}
* @api public
*/
function driver(options, fn) {
if ('function' == typeof options) fn = options, options = {};
options = options || {};
fn = fn || phantom;
var nightmare = new Nightmare(options);
return function phantom_driver(ctx, done) {
debug('going to %s', ctx.url);
nightmare
.on('error', error)
.on('timeout', function(timeout) {
return done(new Error(timeout));
})
.on('resourceReceived', function(resource) {
if (normalize(resource.url) == normalize(ctx.url)) {
debug('got response from %s: %s', resource.url, resource.status);
ctx.status = resource.status;
};
})
.on('urlChanged', function(url) {
debug('redirect: %s', url);
ctx.url = url;
})
wrapfn(fn, select)(ctx, nightmare);
function select(err, ret) {
if (err) return done(err);
nightmare
.evaluate(function() {
return document.documentElement.outerHTML;
}, function(body) {
ctx.body = body;
})
.run(function(err) {
if (err) return done(err);
debug('%s - %s', ctx.url, ctx.status);
done(null, ctx);
});
};
}
}
/**
* Default phantom driver
*
* @param {HTTP Context} ctx
* @param {Nightmare} nightmare
* @param {Function} fn
*/
function phantom(ctx, nightmare) {
return nightmare.goto(ctx.url);
}
/**
* Phantom errors go here
*
* @param {String} msg
*/
function error(msg) {
debug('client-side javascript error %s', msg);
}