Google Cloud Functions包括私有库 [英] Google Cloud Functions include private library

查看:106
本文介绍了Google Cloud Functions包括私有库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在node中编写一个自定义库,我想将其包含在我的Cloud Functions中.由于这是共享代码,因此我希望能够在我的所有Cloud Functions中使用它.

I'm looking to write a custom library in node and I'd like to include that with my Cloud Functions. Since this is shared code, I'd like to be able to use it across all my Cloud Functions.

编写共享代码库并由多个Cloud Functions访问的最佳方法是什么.

What's the best way to write a library of shared code and have that accessed by multiple Cloud Functions.

例如,假设我有两个Cloud Function,即functionA和functionB.

For example, say I have two Cloud Functions, functionA and functionB.

我有一个名为"common.js"的节点javascript文件,该文件具有我要向functionA和functionB公开的javascript函数.

I have a node javascript file called "common.js" that has a javascript function that I'd like to expose to both functionA and functionB.

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

因此在functionA中,我需要此文件并调用"common.log('test');".

So in functionA I'd like to require this file and call "common.log('test');".

我认为这是最基本的问题,但老实说我找不到任何答案.

I see this as the most basic of questions but I honestly can't find an answer anywhere.

任何帮助将不胜感激.从字面上看,这是阻止我使用GCF作为现在和将来开发代码的唯一方法!

Any help would be most appreciated. This is literally the ONLY thing preventing me from using GCF as the way I develop code now and into the future!

推荐答案

如果使用 gcloud 命令行工具来部署您的功能,它将上载本地目录中的所有 1 文件,因此,任何正常的Node.js包含/要求方法都应该起作用.

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返回的对象中引用它.见下文.

In Node.js, writing require('./lib/common') will include the common.js file in the lib subdirectory. Since your file exports an object named common you can reference it directly off the returned object from require. See below.

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

部署

$ gcloud functions deploy helloWorld --trigger-http

注意

1 当前,除非您指定--include-ignored-files,否则gcloud不会上传npm_modules/目录(请参阅

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

这篇关于Google Cloud Functions包括私有库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆