This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
forked from brandonmp/x-ray-puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (49 loc) · 1.61 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
/**
* Module Dependencies
*/
var debug = require('debug')('x-ray:puppeteer');
var Puppeteer = require('puppeteer');
/**
* Export `driver`
*/
/**
* Initialize the `driver`
* with the following `options`
*
* @param {Object} options
* @param {Function} fn
* @ param {Object} [goto_options] Options that'll pass to Puppeteer's .goto() method.
* @ param {String} [waitForSelector] A css selector that Puppeteer ought to wait for after executing goto()
* @return {Function}
* @api public
*/
const driver = (options, fn, goto_options = {}, waitForSelector) => {
// create above returned function's scope so
// we re-use the same chromium page each time
let page, browser;
return fn
? fn(ctx, done)
: async (ctx, done) => {
if (!browser) browser = await Puppeteer.launch(options);
if (!page) page = await browser.newPage();
debug('going to %s', ctx.url);
try {
await page.goto(ctx.url, goto_options);
if (typeof waitForSelector === 'string') {
await page.waitFor(waitForSelector);
}
const html = await page.content();
debug(
'got response from %s, content length: %s',
ctx.url,
(html || '').length
);
ctx.body = html;
done(null, ctx);
} catch (err) {
debug('Puppeteer error', err);
if (err) return done(err);
}
};
};
module.exports = driver;