我有一个很长的 txt
文件,其中包含约 1000 个 url,需要执行它来预热 varnish 缓存。
由于我需要 puppeteer,是否存在通过 AJAX 调用加载的重要内容。
这是我的第一次尝试,但不是 node 的高手。
真正的问题是它产生了 100% 的负载,并启动了太多线程。
const puppeteer = require('puppeteer');
const readline = require('readline');
const fs = require('fs');
const rl = readline.createInterface({
input: fs.createReadStream('varnish-warmer.txt')
});
rl.on('line', (line) => {
(async () => {
if (line != '') {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(line);
await page.waitFor(1000);
browser.close();
}
})();
});
最佳答案
正如您已经注意到的,您的代码会并行启动所有浏览器,这会使您的系统过载。您可以一个接一个地访问每个 URL(选项 1)或使用 pool of browsers加快流程(选项 2)。
选项 1
启动一个浏览器并依次访问所有页面:
const puppeteer = require('puppeteer');
const fs = require('fs');
const lines = fs.readFileSync('varnish-warmer.txt').toString().split('\n');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
for (const line of lines) {
await page.goto(line);
await page.waitFor(1000);
}
await browser.close();
})();
选项 2
由于选项 1 对于 1000 个 URL 可能需要一段时间,您可能希望使用浏览器池来并行访问页面并加快速度。您可以使用 puppeteer-cluster为此(免责声明:我是图书馆的作者)。
const { Cluster } = require('puppeteer-cluster');
const fs = require('fs');
(async () => {
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_BROWSER,
maxConcurrency: 10, // how many URLs should be visited in parallel
// monitor: true, // uncomment to see information about progress
});
// Define the task for each URL
await cluster.task(async ({ page, data: url }) => {
await page.goto(url);
await page.waitFor(1000);
});
// Queue the URLs
const lines = fs.readFileSync('varnish-warmer.txt').toString().split('\n');
lines.forEach(line => cluster.queue(line));
// Wait for the tasks to finish and close the cluster after that
await cluster.idle();
await cluster.close();
})();
您可以使用 maxConcurrency
的值来根据系统的能力(CPU/内存)更改工作程序的数量。
关于javascript - 我怎样才能使用 puppeteer 作为 cachewarmer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55057539/