我目前正在学习 puppeteer 和 firebase。我想要做的是创建网页的 pdf 并上传到 firebase 存储。这是我的代码。
const puppeteer = require('puppeteer');
const fs = require('fs').promises;
const firebase = require('firebase');
require("firebase/storage");
const url = process.argv[2];
if (!url) {
throw "Please provide URL as a first argument";
}
var firebaseConfig = {
#Firebase Config Goes here
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
#Function to generate PDF file
async function run () {
const browser = await puppeteer.launch();
const page = await browser.newPage();
//await page.goto(url);
await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 60000} );
//await page.pdf({ path: 'api.pdf', format: 'A4' })
const myPdf = await page.pdf();
await browser.close()
return myPdf;
}
const myOutput = run();
#Upload to Firebase based on the instruction here https://firebase.google.com/docs/storage/web/upload-files
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
storageRef.child("Name.pdf").put(myOutput)
但是,我在执行代码时遇到了这个错误
$ node screenshot.js https://google.com
Promise { <pending> }
(node:20636) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'byteLength' of undefined
at C:\Users\ppham\NucampFolder\Test\node_modules\@firebase\storage\dist\index.cjs.js:833:40
at Array.forEach (<anonymous>)
at Function.FbsBlob.getBlob (C:\Users\ppham\NucampFolder\Test\node_modules\@firebase\storage\dist\index.cjs.js:832:25)
at multipartUpload (C:\Users\ppham\NucampFolder\Test\node_modules\@firebase\storage\dist\index.cjs.js:1519:24)
at C:\Users\ppham\NucampFolder\Test\node_modules\@firebase\storage\dist\index.cjs.js:2003:31
at C:\Users\ppham\NucampFolder\Test\node_modules\@firebase\storage\dist\index.cjs.js:1900:21
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:20636) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20636) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
这似乎暗示 myOutput 不包含任何内容。我以为我在执行 run() 函数后创建了 pdf 文件,将其分配给 myOutput 变量并将其传递给上传函数?我一直在阅读 Puppeteer 文档,但找不到任何不起作用的原因。有人知道为什么这是无效的吗?
答案 0 :(得分:0)
例如,您的代码与 https://www.toptal.com/puppeteer/headless-browser-puppeteer-tutorial 处的示例代码之间的区别是微不足道的,但有一个显着区别:
run
被定义为一个 async
函数——在示例代码中,这可能无关紧要,因为示例的最后一行只调用了 run()
,之后没有任何反应。但是,在您的代码中,您希望对该输出执行某些操作。所以,你需要调用它:
const myOutput = await run();
但是,Node 不希望您在顶层使用 await
- await 只能在 async
函数内使用。因此,您可以使用 then()
或仅定义另一个异步包装器。所以,大概是这样的:
async function runAndUpload() {
const myOutput = await run();
console.log(myOutput); //let's make sure there's output
var storageRef = firebase.storage().ref();
storageRef.child("Name.pdf").put(myOutput)
}
runAndUpload();