index.js
import puppeteer from 'puppeteer'
// Route 1 # Google
fastify.get('/google', async (request, reply) => {
const browser = await puppeteer.launch({
headless,
args: ['--no-sandbox'],
})
const page = await browser.newPage()
await page.goto('https://google.com', { waitUntil: 'networkidle2' })
const data = await page.evaluate(() => {
const body = document.querySelector('body').textContent
return { body }
})
})
// Router 2 # Bing
fastify.get('/bing', async (request, reply) => {
const browser = await puppeteer.launch({
headless,
args: ['--no-sandbox'],
})
const page = await browser.newPage()
await page.goto('https://bing.com', { waitUntil: 'networkidle2' })
const data = await page.evaluate(() => {
const body = document.querySelector('body').textContent
return { body }
})
})
// Run the server!
const start = async () => {
try {
await fastify.listen({ port })
console.log(' Fastify Server Listening on Port 3000')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
Is there a way to use browser
and page
globally? Above example each router generate browser
every single request. I think it is not proper use case - will occurr memory leak I guess. Is there a way initiate browser
on first launching server and reuse it each router?