使用Node.js Puppeteer遍历页面数组时触发EventEmitter内存泄漏警告
Hey there, let's break down why you're seeing those memory leak warnings and how to fix them.
First, the root cause: every time you navigate to a new page, you're probably adding event listeners (like request, framedetached, or lifecycleevent) to the same page/browser context instance without removing them afterward. Over time, these listeners pile up past Node.js's default limit of 11 per EventEmitter, triggering the warning.
Here are the most effective fixes, ordered by best practice:
1. Clean Up Listeners When Done With a Page
This is the proper long-term fix—always remove listeners when you no longer need them, especially before closing a page. Define your listener functions as named variables so you can reference them when removing:
// Example with Puppeteer (common for this use case) const pageUrls = ["https://example.com/page1", "https://example.com/page2", ...]; for (const url of pageUrls) { const page = await browser.newPage(); // Define named listener functions const handleRequest = (request) => { // Your request handling logic here }; const handleFrameDetach = () => { // Your framedetached logic here }; const handleLifecycle = (event) => { // Your lifecycleevent logic here }; // Add listeners page.on("request", handleRequest); page.on("framedetached", handleFrameDetach); page.on("lifecycleevent", handleLifecycle); // Navigate and run your page operations await page.goto(url); // ... do your scraping/automation tasks ... // Clean up: remove all listeners before closing page.removeListener("request", handleRequest); page.removeListener("framedetached", handleFrameDetach); page.removeListener("lifecycleevent", handleLifecycle); // Close the page to free up resources await page.close(); }
2. Use once() Instead of on() (If Listeners Only Need to Run Once)
If your listener logic only needs to execute a single time per page, use once() instead of on(). This automatically removes the listener after it fires once, preventing accumulation:
page.once("request", (request) => { // This listener will be removed after its first execution });
3. Increase Listener Limits (Last Resort)
Only use this if you absolutely need more than 11 listeners on a single EventEmitter. It's a band-aid, not a fix for the underlying leak, but it will suppress the warning:
// Increase limit for a specific page instance page.setMaxListeners(20); // Set to 0 for unlimited // Or globally increase the default for all EventEmitters require("events").EventEmitter.defaultMaxListeners = 20;
Pro Tip
Always make sure you're properly closing pages/browser contexts after use. Lingering page objects with attached listeners are a common source of memory leaks in automation workflows.
内容的提问来源于stack exchange,提问作者MaxioN

