-
Notifications
You must be signed in to change notification settings - Fork 38
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
kevva
wants to merge
10
commits into
master
Choose a base branch
from
puppeteer
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
12373a4
Replace PhantomJS with Puppeteer
kevva 6720fd7
Add missing `devDependencies`
kevva 08c161e
Add `launch` method to `Screenshot` class
kevva 3cfae93
Typo
kevva 53c5ee4
Minor readme tweaks
sindresorhus 0fc17a3
Support Node.js >=8
kevva 74864f4
Make sure `cookies` is an `Array`
kevva f31a09b
Add `keepAlive` and `browser` options
kevva 3bfddc5
Use local fixtures
kevva 14a0354
Always use `addScriptTag` and `addStyleTag`
kevva File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
node_modules | ||
yarn.lock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
package-lock=false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,5 +2,3 @@ sudo: false | |
language: node_js | ||
node_js: | ||
- '8' | ||
- '6' | ||
- '4' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
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; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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": "*" | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.