1
votes

I want to take a screenshot of a webpage, but no matter what I do puppeteer always crashes。

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({
        headless: false
    });
    const page = await browser.newPage();  
    await page.goto('https://www.google.com/'); 
    await page.screenshot({path: 'screenshot/example.png'}); 
    await page.waitFor(5 * 1000); 
    await browser.close(); 
})();

I saved the above code as web.js, and executed node web.js in cmd. It crashed 2 seconds after the Chrome window appeared, and the page did not load。

(node:27064) UnhandledPromiseRejectionWarning: # (Use node --trace-warnings ... to show where the warning was created) (node:27064) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:27064) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1
Unhandled promise means you forgot your try-catch over this block. Just put it there and inside your catch, check what error is thrown.Wiktor Zychla

1 Answers

1
votes

you've to add an error handler to your promise.
As soon your promised (in this case your async function) throws any error, it reaches the execution root, which in nodejs will cause the app to "crash".
Just call your function like this:

(async () => {
    /* your code here */
})().catch(error => { console.error("Something bad happend...", error); });
``´