html-pdf在Firebase云功能中运行非常慢

问题描述

我开发了一种功能,该功能接受一页HTML,使用htmp-pdf软件包将其转换为PDF,然后上传到Firebase存储。当我从我的PC运行此功能时,它花费不到5秒,但是当我从Firebase功能运行时,它需要花费6分钟。这是代码

  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);
      });
    });

变量“ estadoCuenta”包含要转换的html。

这是我的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"
  }
}

非常感谢您的帮助。

解决方法

这是因为分配给功能的计算资源无法与您的本地设备相比。

云功能上的CPU速度与此document中提到的分配的内存成正比,请尝试为您的功能设置2GB内存。

拥有更多处理资源,您的功能将更快。

如果该功能没有在可接受的时间内响应您,则下一步是使用另一种无服务器产品,例如App EngineCloud Run,该产品允许您为应用程序设置更多资源。 / p>

这些更改将影响您的账单。

,

我调整了您的示例,它对我非常有用,因为它的HTML文件非常小,内存分配为256MB。我保留了您的包裹,以尝试重新使用。我使用了一个内联的非常小的HTML文档,使用了Node.JS 12并替换了例如filefs。我不是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;

对于本地调试,我添加了以下内容:

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

app.get("/",convertor);

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

package.json中有很多依赖项,我想您都需要它们。部署到Cloud Functions时,无需导入express

注意 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.