我有一个包含数百个html文件的文件夹。我需要对每个屏幕截图进行截图,我认为我可以在Gulp任务中使用Puppeteer。
function takeScreenshots() {
return gulp.src(path.join(paths.dest.stage, "**/*.html"))
.pipe(tap(async (file) => {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.setViewport({
width: 1024,
height: 768,
deviceScaleFactor: 1,
});
await page.goto("file://" + file.path);
await page.screenshot({ path: path.join(path.dirname(file.path), path.basename(file.basename, ".html") + ".jpg"), quality: 10 });
await browser.close();
}));
}
当我运行此程序时,我的计算机的风扇打开了,东西锁住了,我收到此消息:
(node:85389) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners added to [process]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
[我认为它正在尝试同时制作所有屏幕截图,但我不知道如何告诉它拍摄一张,完成然后移到下一张,等等。
我进行了快速搜索,但是没有找到任何同步管道的方法。所以我写了一个解决方法。
1-首先,您将使用管道和自来水将所有文件添加到“文件”数组中
2-然后在“结束”事件中订阅
3-然后编写取决于文件数组的业务逻辑
function takeScreenshots() {
const files = [];
return gulp
.src(path.join(paths.dest.stage, "**/*.html"))
.pipe(
tap((file) => {
files.push(file);
})
)
.on("end", async () => {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.setViewport({
width: 1024,
height: 768,
deviceScaleFactor: 1,
});
for (let i = 0, len = files.length; i < len; i++) {
const file = files[i];
await page.goto("file://" + file.path);
await page.screenshot({
path: path.join(
path.dirname(file.path),
path.basename(file.basename, ".html") + ".jpg"
),
quality: 10,
});
await browser.close();
}
});
}