thomasdondorf / puppeteer-cluster

Puppeteer Pool, run a cluster of instances in parallel
MIT License
3.2k stars 307 forks source link
cluster headless-chrome node pool pooling puppeteer

Puppeteer Cluster

Build Status npm npm download count Coverage Status Known Vulnerabilities MIT License

Create a cluster of puppeteer workers. This library spawns a pool of Chromium instances via Puppeteer and helps to keep track of jobs and errors. This is helpful if you want to crawl multiple pages or run tests in parallel. Puppeteer Cluster takes care of reusing Chromium and restarting the browser in case of errors.

What does this library do?

Installation

Install using your favorite package manager:

npm install --save puppeteer # in case you don't already have it installed 
npm install --save puppeteer-cluster

Alternatively, use yarn:

yarn add puppeteer puppeteer-cluster

Usage

The following is a typical example of using puppeteer-cluster. A cluster is created with 2 concurrent workers. Then a task is defined which includes going to the URL and taking a screenshot. We then queue two jobs and wait for the cluster to finish.

const { Cluster } = require('puppeteer-cluster');

(async () => {
  const cluster = await Cluster.launch({
    concurrency: Cluster.CONCURRENCY_CONTEXT,
    maxConcurrency: 2,
  });

  await cluster.task(async ({ page, data: url }) => {
    await page.goto(url);
    const screen = await page.screenshot();
    // Store screenshot, do something else
  });

  cluster.queue('http://www.google.com/');
  cluster.queue('http://www.wikipedia.org/');
  // many more pages

  await cluster.idle();
  await cluster.close();
})();

Examples

Concurrency implementations

There are different concurrency models, which define how isolated each job is run. You can set it in the options when calling Cluster.launch. The default option is Cluster.CONCURRENCY_CONTEXT, but it is recommended to always specify which one you want to use.

Concurrency Description Shared data
CONCURRENCY_PAGE One Page for each URL Shares everything (cookies, localStorage, etc.) between jobs.
CONCURRENCY_CONTEXT Incognito page (see BrowserContext) for each URL No shared data.
CONCURRENCY_BROWSER One browser (using an incognito page) per URL. If one browser instance crashes for any reason, this will not affect other jobs. No shared data.
Custom concurrency (experimental) You can create your own concurrency implementation. Copy one of the files of the concurrency/built-in directory and implement ConcurrencyImplementation. Then provide the class to the option concurrency. This part of the library is currently experimental and might break in the future, even in a minor version upgrade while the version has not reached 1.0. Depends on your implementation

Typings for input/output (via TypeScript Generics)

To allow proper type checks with TypeScript you can provide generics. In case no types are provided, any is assumed for input and output. See the following minimal example or check out the more complex typings example for more information.

  const cluster: Cluster<string, number> = await Cluster.launch(/* ... */);

  await cluster.task(async ({ page, data }) => {
    // TypeScript knows that data is a string and expects this function to return a number
    return 123;
  });

  // Typescript expects a string as argument ...
  cluster.queue('http://...');

  // ... and will return a number when execute is called.
  const result = await cluster.execute('https://www.google.com');

Debugging

Try to checkout the puppeteer debugging tips first. Your problem might not be related to puppeteer-cluster, but puppteer itself. Additionally, you can enable verbose logging to see which data is consumed by which worker and some other cluster information. Set the DEBUG environment variable to puppeteer-cluster:*. See an example below or checkout the debug docs for more information.

# Linux
DEBUG='puppeteer-cluster:*' node examples/minimal
# Windows Powershell
$env:DEBUG='puppeteer-cluster:*';node examples/minimal

API

class: Cluster

Cluster module provides a method to launch a cluster of Chromium instances.

event: 'taskerror'

Emitted when a queued task ends in an error for some reason. Reasons might be a network error, your code throwing an error, timeout hit, etc. The first argument will the error itself. The second argument is the URL or data of the job (as given to Cluster.queue). If retryLimit is set to a value greater than 0, the cluster will automatically requeue the job and retry it again later. The third argument is a boolean which indicates whether this task will be retried. In case the task was queued via Cluster.execute there will be no event fired.

  cluster.on('taskerror', (err, data, willRetry) => {
      if (willRetry) {
        console.warn(`Encountered an error while crawling ${data}. ${err.message}\nThis job will be retried`);
      } else {
        console.error(`Failed to crawl ${data}: ${err.message}`);
      }
  });

event: 'queue'

Emitted when a task is queued via Cluster.queue or Cluster.execute. The first argument is the object containing the data (if any data is provided). The second argument is the queued function (if any). In case only a function is provided via Cluster.queue or Cluster.execute, the first argument will be undefined. If only data is provided, the second argument will be undefined.

Cluster.launch(options)

The method launches a cluster instance.

cluster.task(taskFunction)

Specifies a task for the cluster. A task is called for each job you queue via Cluster.queue. Alternatively you can directly queue the function that you want to be executed. See Cluster.queue for an example.

cluster.queue([data] [, taskFunction])

Puts a URL or data into the queue. Alternatively (or even additionally) you can queue functions. See the examples about function queuing for more information: (Simple function queuing, complex function queuing).

Be aware that this function only returns a Promise for backward compatibility reasons. This function does not run asynchronously and will immediately return.

cluster.execute([data] [, taskFunction])

Works like Cluster.queue, but this function returns a Promise which will be resolved after the task is executed. That means, that the job is still queued, but the script will wait for it to be finished. In case an error happens during the execution, this function will reject the Promise with the thrown error. There will be no "taskerror" event fired. In addition, tasks queued via execute will ignore "retryLimit" and "retryDelay". For an example see the Execute example.

cluster.idle()

Promise is resolved when the queue becomes empty.

cluster.close()

Closes the cluster and all opened Chromium instances including all open pages (if any were opened). It is recommended to run Cluster.idle before calling this function. The Cluster object itself is considered to be disposed and cannot be used anymore.

License

MIT license.