Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace PhantomJS with Puppeteer #46

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
2 changes: 0 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,3 @@ sudo: false
language: node_js
node_js:
- '8'
- '6'
- '4'
4 changes: 2 additions & 2 deletions fixtures/server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict';
const http = require('http');
const cookie = require('cookie');
const getPort = require('get-port');
const pify = require('pify');
const toughCookie = require('tough-cookie');

module.exports = opts => {
opts = opts || {};
Expand All @@ -24,7 +24,7 @@ module.exports = opts => {
});

s.on('/cookies', (req, res) => {
const color = cookie.parse(req.headers.cookie).color || 'white';
const color = toughCookie.parse(req.headers.cookie).value || 'white';
const style = [
`background-color: ${color}; position: absolute;`,
'top: 0; right: 0; bottom: 0; left: 0;'
Expand Down
179 changes: 101 additions & 78 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,85 +1,108 @@
'use strict';
const fs = require('fs');
const path = require('path');
const urlMod = require('url');
const base64Stream = require('base64-stream');
const parseCookiePhantomjs = require('parse-cookie-phantomjs');
const phantomBridge = require('phantom-bridge');
const byline = require('byline');

const handleCookies = (cookies, url) => {
const parsedUrl = urlMod.parse(url);

return (cookies || []).map(x => {
const ret = typeof x === 'string' ? parseCookiePhantomjs(x) : x;

if (!ret.domain) {
ret.domain = parsedUrl.hostname;
}

if (!ret.path) {
ret.path = parsedUrl.path;
}

return ret;
});
const fileUrl = require('file-url');
const isUrl = require('is-url-superb');
const puppeteer = require('puppeteer');
const toughCookie = require('tough-cookie');

const parseCookie = cookie => {
if (typeof cookie === 'object') {
return cookie;
}

const ret = toughCookie.parse(cookie).toJSON();
ret.name = ret.key;
return ret;
};

module.exports = (url, size, opts) => {
const hideElement = element => {
element.style.visibility = 'hidden';
};

const getBoundingClientRect = element => {
const {height, width, x, y} = element.getBoundingClientRect();
return {height, width, x, y};
};

module.exports = async (url, opts) => {
opts = Object.assign({
delay: 0,
scale: 1,
format: 'png'
cookies: [],
fullPage: true,
hide: [],
width: 1920,
height: 1080
}, opts);

const args = Object.assign(opts, {
url,
width: size.split(/x/i)[0] * opts.scale,
height: size.split(/x/i)[1] * opts.scale,
cookies: handleCookies(opts.cookies, url),
format: opts.format === 'jpg' ? 'jpeg' : opts.format,
css: /\.css$/.test(opts.css) ? fs.readFileSync(opts.css, 'utf8') : opts.css,
script: /\.js$/.test(opts.script) ? fs.readFileSync(opts.script, 'utf8') : opts.script
});

const cp = phantomBridge(path.join(__dirname, 'stream.js'), [
'--ignore-ssl-errors=true',
'--local-to-remote-url-access=true',
'--ssl-protocol=any',
JSON.stringify(args)
]);

const stream = base64Stream.decode();

process.stderr.setMaxListeners(0);

cp.stderr.setEncoding('utf8');
cp.stdout.pipe(stream);

byline(cp.stderr).on('data', data => {
data = data.trim();

if (/ phantomjs\[/.test(data)) {
return;
}

if (/http:\/\/requirejs.org\/docs\/errors.html#mismatch/.test(data)) {
return;
}

if (data.startsWith('WARN: ')) {
stream.emit('warning', data.replace(/^WARN: /, ''));
stream.emit('warn', data.replace(/^WARN: /, '')); // TODO: deprecate this event in v5
return;
}

if (data.length > 0) {
const err = new Error(data);
err.noStack = true;
cp.stdout.unpipe(stream);
stream.emit('error', err);
}
});

return stream;
const uri = isUrl(url) ? url : fileUrl(url);
const {
cookies, crop, format, headers, height, hide, keepAlive, password, scale,
script, selector, timeout, transparent, userAgent, username, width
} = opts;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels like overusing destructuring just for the sake of it. And using opts.cookies in the code makes it more explicit it's coming from a user option.


opts.type = format === 'jpg' ? 'jpeg' : format;

if (crop) {
opts.fullPage = false;
}

if (timeout) {
opts.timeout = timeout * 1000;
}

if (transparent) {
opts.omitBackground = true;
}

const browser = opts.browser || await puppeteer.launch();
const page = await browser.newPage();
const viewport = {
height,
width,
deviceScaleFactor: typeof scale === 'number' ? scale : null
};

if (username && password) {
await page.authenticate({username, password});
}

if (Array.isArray(cookies) && cookies.length > 0) {
await Promise.all(cookies.map(x => page.setCookie(parseCookie(x))));
}

if (typeof headers === 'object') {
await page.setExtraHTTPHeaders(headers);
}

if (userAgent) {
await page.setUserAgent(userAgent);
}

await page.setViewport(viewport);
await page.goto(uri, opts);

if (script) {
const fn = isUrl(script) ? page.addScriptTag : script.endsWith('.js') ? page.injectFile : page.evaluate;
Copy link
Collaborator

@SamVerschueren SamVerschueren Oct 4, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we could write this line like this

const fn = isUrl(script) || script.endsWith('.js') ? page.addScriptTag : page.evaluate;

A script tag works for a local file as well right? If not, I think we should wrap the second block in parentheses for readability.

const fn = isUrl(script) ? page.addScriptTag : (script.endsWith('.js') ? page.injectFile : page.evaluate);

await fn(script);
}

if (Array.isArray(hide) && hide.length > 0) {
await Promise.all(hide.map(x => page.$eval(x, hideElement)));
}

if (selector) {
await page.waitForSelector(selector, {visible: true});

opts.clip = await page.$eval(selector, getBoundingClientRect);
opts.fullPage = false;
}

const buf = await page.screenshot(opts);
await page.close();

if (keepAlive !== true) {
await browser.close();
}

return buf;
};

module.exports.startBrowser = puppeteer.launch;
22 changes: 5 additions & 17 deletions license
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
The MIT License (MIT)
MIT License

Copyright (c) Kevin Mårtensson <[email protected]>
Copyright (c) Kevin Mårtensson <[email protected]> (github.com/kevva)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
113 changes: 48 additions & 65 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,67 +1,50 @@
{
"name": "screenshot-stream",
"version": "4.2.0",
"description": "Capture screenshot of a website and return it as a stream",
"license": "MIT",
"repository": "kevva/screenshot-stream",
"author": {
"name": "Kevin Mårtensson",
"email": "[email protected]",
"url": "github.com/kevva"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js",
"stream.js"
],
"keywords": [
"image",
"page",
"phantom",
"phantomjs",
"resolution",
"screen",
"screenshot",
"size",
"stream",
"url"
],
"dependencies": {
"base64-stream": "^0.1.2",
"byline": "^4.2.1",
"object-assign": "^4.0.1",
"parse-cookie-phantomjs": "^1.0.0",
"phantom-bridge": "^2.0.0"
},
"devDependencies": {
"ava": "*",
"cookie": "^0.3.1",
"get-port": "^3.1.0",
"get-stream": "^3.0.0",
"image-size": "^0.5.4",
"is-jpg": "^1.0.0",
"is-png": "^1.0.0",
"pify": "^3.0.0",
"png-js": "^0.1.1",
"xo": "*"
},
"xo": {
"esnext": true,
"overrides": [
{
"files": "stream.js",
"esnext": false,
"rules": {
"import/no-extraneous-dependencies": 0,
"import/no-unresolved": 0,
"no-multi-assign": 0
}
}
]
}
"name": "screenshot-stream",
"version": "4.2.0",
"description": "Capture screenshot of a website and return it as a stream",
"license": "MIT",
"repository": "kevva/screenshot-stream",
"author": {
"name": "Kevin Mårtensson",
"email": "[email protected]",
"url": "github.com/kevva"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"image",
"page",
"phantom",
"phantomjs",
"resolution",
"screen",
"screenshot",
"size",
"stream",
"url"
],
"dependencies": {
"file-url": "^2.0.2",
"is-url-superb": "^2.0.0",
"parse-resolution": "^1.0.0",
"puppeteer": "^0.11.0",
"tough-cookie": "^2.3.3"
},
"devDependencies": {
"ava": "*",
"get-port": "^3.2.0",
"image-size": "^0.6.1",
"is-jpg": "^1.0.0",
"is-png": "^1.1.0",
"pify": "^3.0.0",
"png-js": "^0.1.1",
"xo": "*"
}
}
Loading