Categories
express google-app-engine javascript node.js puppeteer

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