Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Google App engine Nodejs Puppeteer

This code works in local, but when I deploy to Google App Engine I got the error "Browser var is not defined". How can I define globally the browser variable in better way? My goal is to launch puppeteer browser at startup and use the same instance to open a new webpage for each HTTP request.

const puppeteer = require('puppeteer');
const express   = require('express');
const fs        = require('fs');
var port        = process.env.PORT || 80;
const app       = express();

app.get('/request',  async (req, res, next) => {

  console.log(browser)

   //using browser var here   <---
   // UnhandledPromiseRejectionWarning: ReferenceError: browser is not defined

});

app.listen(port, () => {
  console.log('Listening on PORT: ', port)
  setup()
});

const setup = async function(){

  console.log("Initializing Puppeteer...")
  global.browser = await puppeteer.launch({
      args: [
      '--no-sandbox', 
      '--disable-setuid-sandbox', 
      '--disable-dev-shm-usage=true',
      '--disable-accelerated-2d-canvas=true',
      '--disable-gpu', 
      ]
  });

browser.on('disconnected', setup);

console.log(`Started Puppeteer with pid ${browser.process().pid}`);
}

app.yml

runtime: nodejs10
env: standard
instance_class: F4_HIGHMEM
automatic_scaling:
  max_instances: 15
  min_instances: 0
  max_pending_latency: 10ms
  max_concurrent_requests: 1
like image 789
sparkle Avatar asked Jan 29 '20 12:01

sparkle


Video Answer


1 Answers

I was able to reproduce your use case on App Engine Standard:

const puppeteer = require('puppeteer');
const express   = require('express');
const fs        = require('fs');
var port        = process.env.PORT || 80;
const app       = express();

global.browser = null;

const setup = async function(){

  console.log("Initializing Puppeteer...")
  browser = await puppeteer.launch({
      args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage=true',
      '--disable-accelerated-2d-canvas=true',
      '--disable-gpu',
      ]
  });


browser.on('disconnected', setup);

}




app.get('/', (req, res) => {
  setup();
  console.log(`Started Puppeteer with pid ${browser.process().pid}`);
  res.status(200).send('Hello, world!').end();
});




// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {

  setup();
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END gae_node_request_example]

module.exports = app;

enter image description here

like image 78
marian.vladoi Avatar answered Oct 24 '22 06:10

marian.vladoi