1

I'm Trying to take a screenshot from a website using the package puppeteer

For this I create a simple server with Express:

app.get('/requestScreenShootForDesktop/:id', function(req, res){
    (async () => {
        const pathUpload = 'uploads/' + Math.floor(Date.now() / 1000) + '.png';
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(this.req.params.id);
        await page.setViewport({width: 1920, height: 1080});
        await page.screenshot({path: pathUpload});

        await browser.close();
        await res.send({msg: 'ScreenShot Ok'});
      })();
});

The problem with this code is on line await page.goto(this.req.params.id);, Node says:

Cannot read property 'params' of undefined

This is because the variable req belonging to function app.get doesn't exists in async scope.

How can I solve this problem, and pass my variable to async function ?

3
  • 1
    Why are you using a self invoking function? Commented Apr 28, 2019 at 14:30
  • 2
    The problem is not that req doesn't exist, it's that this.req doesn't exist. Why did you use this? Overall it's not really clear what you intend for that code to do. Commented Apr 28, 2019 at 14:30
  • This is just a typo: this.req should be req. Commented Apr 28, 2019 at 14:48

3 Answers 3

2

Just ditch the IIFE and dont use this to access req

app.get('/requestScreenShootForDesktop/:id', async function(req, res){
    const pathUpload = 'uploads/' + Math.floor(Date.now() / 1000) + '.png';
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto(req.params.id);
    await page.setViewport({width: 1920, height: 1080});
    await page.screenshot({path: pathUpload});

    await browser.close();

    res.send({msg: 'ScreenShot Ok'});
});
Sign up to request clarification or add additional context in comments.

6 Comments

What should that change?
my bad I had missed the usage of this
That is still a typo?
whats a typo? please explain or better yet, answer
this.res vs res. Thats just a typo.
|
0
(async (req, res) => {
    const pathUpload = 'uploads/' + Math.floor(Date.now() / 1000) + '.png';
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(req.params.id);
    await page.setViewport({width: 1920, height: 1080});
    await page.screenshot({path: pathUpload});

    await browser.close();
    await res.send({msg: 'ScreenShot Ok'});
  })(req, res);

1 Comment

There is no sense in using req and res as parameters.
0

You can keep IIFE, but remove this keyword

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.