Szpadel/chrome-headless-render-pdf

Ability to define port number generator function

sillva opened this issue · 2 comments

It would be cool to add to the options object the ability to either manually set the *port number or to inject a function to dynamically generate it.

The default implementation can cause issues on environments where some ports have already been taken.

It gave me a bit of headache as chrome endlessly tried to send instructions to an app already running on the port generated by the following statement:

  • this.port = Math.floor(Math.random() * 10000 + 1000);

To overtake that issue I created my own function that is a copy of the static method "generateSinglePdf"

let generatePDF = async (url, filename, options) => {
    const renderer = new RenderPDF(options)
    renderer.port = generatePortNumber()
    await renderer.connectToChrome()
    try {
        const buff = await renderer.renderPdf(url, renderer.generatePdfOptions())
        fs.writeFileSync(filename, buff);
        renderer.log(`Saved ${filename}`)
    } catch (e) {
        renderer.error('error:', e)
    }
    renderer.killChrome()
}

This function will generate port numbers within a determined range (6000-7000)

let generatePortNumber = () => {
    const min = 6000
    const max = 7000
    return Math.floor(Math.random() * (max - min + 1)) + min
}

Isn't spawning dedicated chrome instance outside and use of remoteHost and remotePort enough?
Also I'm thinking about checking if port is open before using it to spawn chrome instance, this should prevent it from using already occupied ports

Hi Szpadel, if I set the remoteHost then I might run into problems with the method killChrome().

Your idea seems interesting however, I am not 100% sure it'd work as the issue I had here was with services already running on the port and getting thousands of calls from remote chrome. I don't know if it possible to check it the port is free or if what is running there is actually an instance of chrome.