0

Hi I am trying to make a screenshot service

const puppeteer = require('puppeteer');
var resWidth = 1366;
var resHeight = 1000;
var browser;

(async () => {
browser = await puppeteer.launch({ignoreHTTPSErrors: true});
});

and when I receive a work I try to do

data.forEach(function(d){
    try {
        console.log(d["url"]);
        (async () => {
            var page = await browser.newPage();
            await page.setViewport({width: resWidth, height: resHeight});
            await page.goto(d["url"], {timeout: 90000, waitUntil: 'networkidle'});
            await page.screenshot({path: './picdata/' + d['id'] + '.png' ,fullPage: true});
            await page.close();
        })();

    } catch(e) {}
});

but I can't... here is the error:

(node:40596) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 7): TypeError: Cannot read property 'newPage' of undefined

I don't want to open a new browser for each screenshot launching browser takes time and requires more memory?

what should I do?

N-Alpr
  • 336
  • 2
  • 11

1 Answers1

1

The problem:

(async () => { browser = await puppeteer.launch({ignoreHTTPSErrors: true}); });

This code never gets executed. Why? because it's not a true closure.

More on closures, here.

That being said, that wont have work for your given scenario, as they are async tasks.

My try with your example:

'use strict';
const puppeteer = require('puppeteer');
const resWidth = 1366;
const resHeight = 1000;
let browser;
let page;

async function launchBrowser() {
  browser = await puppeteer.launch({ headless: true }); //this "{ headless: true }" will ensure a browser window is not open a single time.
};

launchBrowser().then((x) => { // wait until browser has launched
  data.forEach(async (d) => {
    try {
      page = await browser.newPage(); // the document is not very clear about this method, so I am still unsure if I could move this in the above launchBrowser() method. 
      await page.setViewport({ width: resWidth, height: resHeight });
      await page.goto(d['url'], { timeout: 90000, waitUntil: 'networkidle' });
      await page.screenshot({ path: './picdata/' + d['id'] + '.png', fullPage: true });
    }
    catch (e) {
      console.log(e);
      await browser.close(); // close browser if there is an error
    }
  });
})
.then(() => {
  await browser.close(); // close browser finally.
});

Pro Tip: Start using let, const instead of var.

There is a great article on this, here

aitchkhan
  • 1,842
  • 1
  • 18
  • 38