简体   繁体   English

html-pdf 在 firebase 云函数中运行很慢

[英]html-pdf runs very slow in firebase cloud functions

I have developed a function that take an one page HTML, convert it to PDF using htmp-pdf package and upload to firebase storage.我开发了一个 function,它占用一页 HTML,使用 htmp-pdf package 将其转换为 PDF 并上传到 firebase 存储。 When I run this function from my pc it takes less than 5 seconds, but when I run it from firebase function it takes up to 6 minutes.当我从我的电脑运行这个 function 时它需要不到 5 秒,但是当我从 firebase function 运行它时它最多需要 6 分钟。 This is the code:这是代码:

  pdf.create(estadoCuenta, { orientation: 'portrait', type: 'pdf', timeout: '360000' }).toStream(function(err, stream) {
      console.log('Nombre del archivo generado: ' + file.name);
      stream.pipe(file.createWriteStream({
      metadata: {
      contentType: 'application/pdf',
      metadata: {
          origin: 'created by ...'
          }
      },
      public: true,
      validation: "md5"
      }))
      .on('error', function(err) {
          console.log('error en la carga de archivo: ' + err);
      })
      .on('finish', function() {
              // The file upload is complete.
              let estadoCuentaPDF = file.name.replace('/','%2F');
              console.log('estadoCuentaPDF:' + estadoCuentaPDF);
      });
    });

Variable "estadoCuenta" contains the html to convert.变量“estadoCuenta”包含要转换的 html。

This is my package.json:这是我的 package.json:

{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "author": "xxx",
  "repository": "https://yyy@bitbucket.org/zzz/www.git",
  "license": "xxx",
  "private": true,
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "engines": {
    "node": "10"
  },
  "dependencies": {
    "-": "0.0.1",
    "@google-cloud/firestore": "^3.7.5",
    "actions-on-google": "^2.10.0",
    "cors": "^2.8.5",
    "dialogflow": "^1.2.0",
    "dialogflow-fulfillment": "^0.6.1",
    "dotenv": "^8.2.0",
    "envfile": "^6.9.0",
    "express": "^4.17.1",
    "firebase-admin": "^8.0.0",
    "firebase-functions": "^3.6.1",
    "firebase-tools": "^7.4.0",
    "html-pdf": "^2.2.0",
    "isomorphic-fetch": "^2.2.1",
    "node-env-file": "^0.1.8",
    "nodejs-base64": "^1.0.3",
    "nodemailer": "^6.3.0",
    "pg": "^7.18.2",
    "string-similarity": "^3.0.0",
    "twilio": "^3.31.1",
    "unirest": "^0.6.0"
  }
}

This is because the computational resources assigned to a function can't be comparable with your local device.这是因为分配给 function 的计算资源无法与您的本地设备相提并论。

The CPU speed on cloud functions is directly proportional to the Memory assigned as is mentioned in this document , please try to set up 2GB Memory to your function.云函数上的 CPU 速度与本文档中提到的分配的 Memory 成正比,请尝试为您的 function 设置 2GB Memory。

With more processing resources your function will be faster.使用更多的处理资源,您的 function 会更快。

If the function is not responding in an acceptable time for you, the next step is to use another serverless product such as App Engine or Cloud Run that allows you to set more resources to your application.如果 function 没有在您可接受的时间内响应,下一步是使用其他无服务器产品,例如App EngineCloud Run ,它们允许您为应用程序设置更多资源。

These changes will be affect your bill.这些更改将影响您的帐单。

I tweaked your example and it works for me with a very small HTML file and a 256MB memory allocation.我调整了您的示例,它适用于非常小的 HTML 文件和 256MB memory 分配。 I retained your packages to try to repro your usage.我保留了您的包裹以尝试重现您的使用情况。 I used an inline and very small HTML document, I used Node.JS 12 and I replaced eg file with fs .我使用了一个内联且非常小的 HTML 文档,我使用了 Node.JS 12 并将 eg file替换为fs I'm not much of a Node.JS developer so apologies for the poor code.我不是 Node.JS 开发人员,所以为糟糕的代码道歉。

/* jshint esversion: 6 */
/* globals exports,require */

const pdf = require("html-pdf");
const fs = require("fs");

const estadoCuenta = `<html><head><title>Stackoverflow: 63688028</title></head><body><div id="content">Hello Freddie!</div></body></html>`;

const convertor = (req, res) => {

    // Write it
    const options = { orientation: 'portrait', type: 'pdf', timeout: '360000' };
    pdf.create(estadoCuenta, options).toStream(function (err, stream) {
        var writeStream = fs.createWriteStream("/tmp/file.pdf");
        stream.pipe(writeStream).on('error', function (err) {
            console.log(`[stream.pipe] Error: ${err}`);
        }).on('finish', function () {
            // Read it
            var readStream = fs.createReadStream('/tmp/file.pdf');
            var filename = encodeURIComponent("converted.pdf");

            res.setHeader('Content-disposition', `inline; filename="${filename}"`);
            res.setHeader('Content-type', 'application/pdf');

            readStream.pipe(res);
            console.log(`Done`);
        });
    });

};

exports.convertor = convertor;

For local debugging, I appended the following:对于本地调试,我附加了以下内容:

const express = require("express");
const app = express();
const port = 3000;

app.get("/", convertor);

app.listen(port, () => {
    console.log(`Listening: http://localhost:${port}`);
});

There are many dependencies in the package.json and I assume you need them all. package.json中有许多依赖项,我假设您需要它们。 You don't need to import express when you're deploying to Cloud Functions.部署到 Cloud Functions 时不需要导入express

NOTE html-pdf includes a severe vuln:注意html-pdf包含一个严重的漏洞:

=== npm audit security report ===                        
                                                                                
                                                                                
                                 Manual Review                                  
             Some vulnerabilities require your attention to resolve             
                                                                                
          Visit https://go.npm.me/audit-guide for additional guidance           
                                                                                
                                                                                
  Critical        Arbitrary File Read                                           
                                                                                
  Package         html-pdf                                                      
                                                                                
  Patched in      No patch available                                            
                                                                                
  Dependency of   html-pdf                                                      
                                                                                
  Path            html-pdf                                                      
                                                                                
  More info       https://npmjs.com/advisories/1095                             
                                                                                
found 1 critical severity vulnerability in 750 scanned packages
  1 vulnerability requires manual review. See the full report for details.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM