123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- const { PATH_FILES } = require('../config')
- const logger = require('../log/index')
- const puppeteer = require('puppeteer');
- const fs = require('fs')
- const path = require('path')
- // 生成
- async function initBrowser () {
- logger.log.debug('启动', new Date().toLocaleString())
- return await puppeteer.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox']
- });
- }
- let browser = null
- function checkCache (fPath) {
- try {
- const fStat = fs.statSync(fPath)
- if (fStat) {
- const isFile = fStat.isFile()
- if (isFile) {
- return fPath
- }
- }
- return false
- } catch (err) {
- return false
- }
- }
- function wait(ms) {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- console.log("Done waiting");
- resolve(ms)
- }, ms)
- })
- }
- async function createHTMLOfURL (url, config = {}) {
- if (!browser) {
- browser = await initBrowser()
- }
- config = Object.assign( {
- filename: '',
- dir: '',
- nocache: false,
- width: '950px',
- height: '1360px',
- margin: {
- top: 0,
- bottom: 0
- },
- }, config)
- // 文件路径
- const outPath = path.join(PATH_FILES, config.dir)
- const outConfig = Object.assign({path: `${config.filename}.html`, width: config.width, height: config.height,printBackground: true }, config)
- outConfig.path = path.join(outPath, outConfig.path)
- const outFilePath = outConfig.path.slice(0, outConfig.path.lastIndexOf('/'))
- if (!fs.existsSync(outFilePath)) {
- fs.mkdirSync(outFilePath);
- }
- // 检查缓存
- if (!config.nocache) {
- const result = checkCache(outConfig.path)
- if (result) {
- logger.log.debug('命中缓存文件')
- return result
- }
- }
- const page = await browser.newPage();
- try {
- await page.setDefaultNavigationTimeout(0)
- page.on('console', async (message) => {
- const args = await Promise.all(message.args().map(arg => arg.jsonValue()));
- logger.log.debug(`page log: ${message.type()}: ${message.text()} args: ${JSON.stringify(args)}`);
- });
- await page.on('response', (response) => {
- if (response.status() !== 200) {
- logger.log.debug(`Res error: ${response.status()} ${response.url()}`)
- }
- });
- await page.goto(url, {waitUntil: 'networkidle2'});
- // 在网页上执行一些操作,可能触发了 console.log
- await page.evaluate(() => {
- console.warn('Hello from the page!');
- });
- await wait(config.delay || 1000)
- logger.log.debug('等待生成', new Date().toLocaleString())
- const html = await page.evaluate(() => {
- const element = document.querySelector('.analysis-report') || document.querySelector('body');
- return element.outerHTML;
- });
- // 保存生成的HTML到文件
- const fs = require('fs');
- fs.writeFileSync(outConfig.path, html);
- await page.close();
- logger.log.debug('当前时间', new Date().toLocaleString())
- return outConfig.path
- } catch (e) {
- logger.log.debug(e)
- await page.close();
- }
- }
- module.exports = createHTMLOfURL
|