Introduce Page.saveScreenshot

Page.saveScreenshot uses filepath to infer screenshot type (either
PNG of JPG) and saves the screenshot to file system.
This commit is contained in:
Andrey Lushnikov 2017-05-12 10:50:06 -07:00
parent 10d388b9b1
commit 52e2633f32
2 changed files with 20 additions and 10 deletions

View File

@ -17,6 +17,7 @@
var fs = require('fs');
var EventEmitter = require('events');
var helpers = require('./helpers');
var mime = require('mime');
class Page extends EventEmitter {
/**
@ -335,6 +336,24 @@ class Page extends EventEmitter {
return new Buffer(result.data, 'base64');
}
/**
* @param {string} filePath
* @param {?{x: number, y: number, width: number, height: number}} clipRect
* @return {!Promise}
*/
async saveScreenshot(filePath, clipRect) {
var mimeType = mime.lookup(filePath);
var screenshotType = null;
if (mimeType === 'image/png')
screenshotType = Page.ScreenshotTypes.PNG;
else if (mimeType === 'image/jpeg')
screenshotType = Page.ScreenshotTypes.JPG;
if (!screenshotType)
throw new Error(`Cannot render to file ${fileName} - unsupported mimeType ${mimeType}`);
var buffer = await this.screenshot(screenshotType, clipRect);
fs.writeFileSync(filePath, buffer);
}
/**
* @return {!Promise<string>}
*/

View File

@ -226,14 +226,6 @@ class WebPage {
* {string} fileName
*/
render(fileName) {
var mimeType = mime.lookup(fileName);
var screenshotType = null;
if (mimeType === 'image/png')
screenshotType = ScreenshotTypes.PNG;
else if (mimeType === 'image/jpeg')
screenshotType = ScreenshotTypes.JPG;
if (!screenshotType)
throw new Error(`Cannot render to file ${fileName} - unsupported mimeType ${mimeType}`);
var clipRect = null;
if (this.clipRect && (this.clipRect.left || this.clipRect.top || this.clipRect.width || this.clipRect.height)) {
clipRect = {
@ -243,8 +235,7 @@ class WebPage {
height: this.clipRect.height
};
}
var imageBuffer = await(this._page.screenshot(screenshotType, clipRect));
fs.writeFileSync(fileName, imageBuffer);
var imageBuffer = await(this._page.saveScreenshot(fileName, clipRect));
}
release() {