Home » Javascript » javascript – Interacting with already initialized Puppeteer instance via Express endpoint

javascript – Interacting with already initialized Puppeteer instance via Express endpoint

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have an express app with which I interact with a puppeteer instance. In order to achieve this, I do something like this.

**server.js**  

const puppeteer = require('puppeteer');
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const port = process.env.PORT;

// using bodyParser to parse JSON bodies into JS objects
app.use(bodyParser.json());

//  creating a puppeteer instance
let client = await puppeteer.launch(config)

app.post("/open", (req, res) => {
    let page = req.body.page;
    if (page) {
       client.newPage().then(() => res.json({"success" : true})
    }
});

app.listen(port, () =>
    console.log(`App is listening on port ${port}!`)
);

The issue I face with this kind of a setup is, every time I restart my server, my puppeteer instance also needs to restart. My future requirements(long-running task in puppeteer) doesn’t allow me to restart my puppeteer instances each time I close/restart my express server.

So, is there a way I could initialize the puppeteer instance and save a reference to it in some form of storage (disk etc.) in another file, say pup.js and start it, and then interact with it inside my server.js files which now should hold only my server specific code. Thus, basically, I would do node pup.js to start and initialize the puppeteer instance and then do node server.js to start my express server. Basically, make them independent of each other.

How to&Answers: