首页 > 解决方案 > Node.JS Puppeteer:MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。(Heroku 部署)

问题描述

我有一个非常简单的测试应用程序,在本地运行(几乎)没有错误,但是在我的 Heroku 部署中,事情并不顺利。以下是该应用程序的基础知识。

傀儡师选项:

const puppetOptions = {
    defaultViewport: null,
    args: [
        "--incognito",
        "--no-sandbox",
        "--single-process",
        "--no-zygote"
    ],     
}

网站抓取功能:

module.exports.checkWebsite = async (url, int) => {
    console.log(`Scraping site...`);
    // launch a browser
    const browser = await puppeteer.launch(constants.puppetOptions);
    try {
        // open a new page
        const page = await browser.newPage();
        // navigate to URL
        await page.goto(url);
        // Find a specific element on the page
        const element = await page.$('element.class');
        // If the element exists, log success, and clear the setInterval function
        // If not, log it and let the periodic scrape continue
        if (element) {
            console.log(`Element Available...`);
            clearInterval(int)
        } else {
            console.log(`Element Not Available...`);
        }
    } catch (err) {
        console.log(`Website Scrape Error!`, err);
    } finally {
        // Regardless of the outcome, shutdown the browser
        console.log('Closing browser...');
        await browser.close();
        return;
    }
}

然后是基本的服务器运行的东西:

let checkWebsiteRun;
let checkWebsite2Run;

const server = app.listen(process.env.PORT || 5000, () => {

    console.log('Running server...');

    checkWebsiteRun = setInterval(() => {
        checkWebsite("https://google.com", checkWebsiteRun);
    }, 1000 * 60);

    checkWebsite2Run = setInterval(() => {
        checkWebsite("https://yahoo.com", checkWebsite2Run);
    }, 1000 * 60);

})

现在实际上,我一直试图在不同的站点上同时发生大约四个这样的间隔刮擦。似乎我添加的越多,我就越有可能MaxListenersExceededWarning: Possible EventEmitter弹出这个错误。此外,我更有可能TimeoutError: Navigation timeout of 30000 ms exceeded在看似随机的擦伤实例上出错。更令人困惑的是,该应用程序似乎在前几次尝试中表现最差,出现超时错误和最大侦听器错误,但在失败一段时间后似乎趋于平稳并运行得有些平稳。

我想我的主要问题是,我的应用程序中是否有某种清理工作没有执行,或者我在不良实践中是否有一些严重的低效率?也许打开太多无头浏览器?也许关闭并重新打开浏览器而不是刷新页面?也许每个网站都有单独的浏览器抓取?

标签: node.jsherokupuppeteer

解决方案


推荐阅读