nodejs api puppeteer 启动 newPage 不起作用,它会重新启动服务器

时间:2021-05-25 10:21:56

标签: node.js puppeteer nodemon

我正在尝试从调用 api 的 html 模板创建 pdf,所以我正在使用 puppeteer。

问题是,当我尝试从 puppeteer 启动创建一个新页面时,它不起作用并且它重新启动了服务器,我不知道为什么。我在 localhost 上工作,puppeteer 的版本是 ^9.1.1

这是我通过单击 href 链接调用 api 时的代码

    export default async (templateName, { totalPages, currentPage, ...data }) => {
    const browser = await puppeteer.launch({ 
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
      ],
    })
    const html = await handlebars(
    templateName,
    {
      ...data,
    },
  )

  const tmpId = uuidV4()
  const tempFolder = path.join(__dirname, '../', tmpId)
  const tempFilePath = path.join(tempFolder, 'index.html')

  await mkdir(tempFolder)
  await writeFile(tempFilePath, html)
  await copyFolder(
    path.join(__dirname, '../templates', 'quote', 'assets'),
    path.join(tempFolder, 'assets'),
  )

  console.log("here")
  const page = await browser.newPage()
  console.log("after")

  // the code to make the pdf...

  return pdf
 }

这里是api服务器:

import http_errors from 'http-errors';
const { NotFound } = http_errors;
import 'dotenv/config.js'
import './config/init_redis.js'
import express, { json, urlencoded } from "express"
import htmltopdfRouter from "./html_to_pdf/routes/index.js"

const app = express();
import cookieParser from 'cookie-parser'
import cors from 'cors'
app.use(json())
app.use(cookieParser())
app.use(cors({ credentials: true, origin: "http://localhost:8081" }));
app.use(urlencoded({ extended: true }))

app.use("/api", htmltopdfRouter)

app.use(async (req, res, next) => {
  next(NotFound())
})

app.use((err, req, res, next) => { 
  res.status(err.status || 500)
  res.send({
      success: err.status,
      message: err.message,
  })
})

const port = process.env.APP_PORT || 4000;
app.listen(port, () => {
  console.log("Server up and running on PORT :", port);
});

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在编写代码来创建触发 nodemon 的目录和临时文件。

您可以通过编辑启动脚本来排除这些文件夹。

示例

nodemon --ignore 'tmp/*' index.js

Nodemon - exclusion of files