Google Cloud Functions 包含私有库

2023-11-26

我正在寻找在节点中编写一个自定义库,并且希望将其包含在我的云函数中。由于这是共享代码,我希望能够在我的所有云功能中使用它。

编写共享代码库并让多个云函数访问该库的最佳方式是什么?

例如,假设我有两个云函数,functionS 和 function。

我有一个名为“common.js”的节点 javascript 文件,其中有一个我想向 functionA 和 functionB 公开的 javascript 函数。

exports.common = {
    log: function(message) {
        console.log('COMMON: ' + message);
    }
};

所以在 functionA 中我想需要这个文件并调用“common.log('test');”。

我认为这是最基本的问题,但老实说我在任何地方都找不到答案。

非常感激任何的帮助。这实际上是阻止我使用 GCF 作为我现在和未来开发代码的方式的唯一因素!


If you use the gcloud command line tool to deploy your function it will upload all1 the files in your local directory, so any normal Node.js way of doing an include/require should work.

在 Node.js 中,编写require('./lib/common')将包括common.js文件在lib子目录。由于您的文件导出一个名为common您可以直接从返回的对象中引用它require。见下文。

文件布局

./
../
index.js
lib/common.js

index.js

// common.js exports a 'common' object, so reference that directly.
var common = require('./lib/common').common;

exports.helloWorld = function helloWorld(req, res) {
  common.log('An HTTP request has been made!');
  res.status(200);
}

Deploy

$ gcloud functions deploy helloWorld --trigger-http

Note

1 Currently gcloud won't upload npm_modules/ directory unless you specify --include-ignored-files (see gcloud docs)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Cloud Functions 包含私有库 的相关文章

随机推荐