Szpadel / chrome-headless-render-pdf

225 stars 67 forks source link

Ability to define port number generator function #48

Closed sillva closed 5 years ago

sillva commented 5 years ago

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:

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
}
Szpadel commented 5 years ago

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

sillva commented 5 years ago

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.