使用Cloud Functions在GCP上调度Node.js脚本

时间:2019-03-03 20:33:20

标签: node.js google-cloud-platform google-cloud-functions puppeteer

我创建了一个脚本,该脚本从网页上抓取信息并将其写入Google表格。在我的本地计算机上,这很好用,但是我想在GCP上安排它。

听起来像是要使用云函数,但是当我部署函数时,出现此错误:

  

功能在加载用户代码时失败。错误消息:由文件working.js定义的Node.js模块应该导出名为run的函数

我不确定我应该使用什么作为“要执行的功能”。这是我上传的功能:

const puppeteer = require('puppeteer');
const jsonexport = require('jsonexport');
const GoogleSpreadsheet = require('google-spreadsheet');
const creds = require('./google-generated-creds.json');
const fs = require('fs');

var doc = new GoogleSpreadsheet('1qaFi0xnhaCZEduylUvGXWpyMJv00Rz6Y9qqyFR1E9oI');

function run() {
    return new Promise(async (resolve, reject) => {
        try {
            const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
            const page = await browser.newPage();
            const urls = [
            "https://www.marksandspencer.com/pure-cotton-long-sleeve-jumpsuit/p/p60258655?image=SD_01_T42_6701_XB_X_EC_90&color=INDIGO&prevPage=plp",
            "https://www.marksandspencer.com/cotton-rich-striped-3-4-sleeve-t-shirt/p/p60210598?prevPage=plp",
            "https://www.marksandspencer.com/high-neck-long-sleeve-blouse/p/p60260040?image=SD_01_T43_5168_HD_X_EC_90&color=LIGHTDENIM&prevPage=plp",
            "https://www.marksandspencer.com/pure-cotton-printed-short-sleeve-t-shirt/p/p60263529?image=SD_01_T41_8030Z_Z4_X_EC_90&color=WHITEMIX&prevPage=plp",
            "https://www.marksandspencer.com/pure-cotton-button-detailed-denim-mini-skirt/p/p60260145?image=SD_01_T57_4004_QP_X_EC_90&color=DARKINDIGO&prevPage=plp",
            "https://www.marksandspencer.com/pure-cotton-long-sleeve-shirt-midi-dress/p/p60258654?image=SD_01_T42_6703_HP_X_EC_90&color=DENIM&prevPage=plp",
            "https://www.marksandspencer.com/mid-rise-skinny-leg-ankle-grazer-jeans/p/p60220155?prevPage=plp",
            "https://www.marksandspencer.com/pure-cotton-long-sleeve-shirt/p/p60260208?image=SD_01_T43_5181_HP_X_EC_90&color=DENIM&prevPage=plp",
            "https://www.marksandspencer.com/long-sleeve-shirt-mini-dress/p/p60258652?image=SD_01_T42_6704_HP_X_EC_90&color=DENIM&prevPage=plp",
            "https://www.marksandspencer.com/wide-fit-suede-lace-up-trainers/p/p60216277?prevPage=plp",
            "https://www.marksandspencer.com/suede-ankle-boots/p/p60226911?prevPage=plp",
            "https://www.marksandspencer.com/leather-buckle-hip-belt/p/p60186701?prevPage=plp",
            "https://www.marksandspencer.com/cross-body-bag/p/p60215352?prevPage=plp"
            ];
            const productsList = [];
            for (let i = 0; i < urls.length; i++) {
                const url = urls[i];
                await page.goto(url);
                let products = await page.evaluate(() => {
                    let product = document.querySelector('h1[itemprop=name]').innerText;
                    let results = [];
                    let items = document.querySelectorAll('[data-ttip-id=sizeGridTooltip] tbody tr td label');
                    items.forEach((element) => {
                        let size = element.getAttribute('for');
                        let stockLevel = "";
                        let nearest_td = element.closest('td');
                        if (nearest_td.classList.contains('low-stock')) {
                            stockLevel = "Low stock"
                        } else if (nearest_td.classList.contains('out-of-stock')) {
                            stockLevel = "Out of stock"
                        } else {
                            stockLevel = "In stock"
                        }
                        results.push({
                            product: product,
                            size: size,
                            stock: stockLevel
                        })
                    });
                    return results
                })
                productsList.push(products)
            }
            browser.close();

            function flatten(arr) {
                return arr.reduce(function(flat, toFlatten) {
                    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
                }, []);
            }
            var flatProducts = flatten(productsList)
            flatProducts.forEach(function(row) {
                // Authenticate with the Google Spreadsheets API.
                doc.useServiceAccountAuth(creds, function(err) {
                    // Get all of the rows from the spreadsheet.
                    doc.addRow(1, row, function(err, rows) {
                        console.log(row);
                    });
                });
            });

        } catch (e) {
            return reject(e);
        }
    })
}
run().then(console.log).catch(console.error);

我以前从未使用过Cloud Functions,因此不确定需要多少修改脚本。

2 个答案:

答案 0 :(得分:1)

您不能仅上传任何要运行的脚本。您必须使用Cloud tools (via gcloud)Firebase tools and SDK定义一个函数。您还必须弄清楚如何触发它。触发该功能后,您可以安排执行代码。

我要说的是,仅将现有脚本移植到Cloud Functions并不是一件容易的事。您将需要花一些时间来了解系统的工作方式,以便有效地使用它。

答案 1 :(得分:0)

该错误指的是Cloud Functions找不到要在该文件(working.js)中运行的函数,因为您还没有exported。例如,如果您创建一个名为run的Cloud Function,则必须通过将脚本中的函数分配给模块中的exports.run来导出该函数:

exports.run = (event, callback) => {
  callback(null, `Hello ${event.data.name || 'World'}!`);
};

documentation中还有更多示例,但是可能需要对脚本进行其他更改以进行身份​​验证等,才能在GCP上正常工作。