Google Cloud Functions Includes Private Library

I want to write a custom library in node, and I would like to include it in my cloud functions. Since this is generic code, I would like to use it in all my Cloud functions.

What is the best way to write a shared code library and access them through several cloud functions.

For example, let's say I have two cloud functions, functionA and functionB.

I have a javascript node file called "common.js" that has a javascript function that I would like to provide both functions and functions.

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

So, in function A, I would like to require this file and call "common.log ('test');".

I see this as the easiest question, but I honestly can't find the answer anywhere.

Any help would be greatly appreciated. This is literally the only thing that prevents me from using GCF as a way to develop code now and in the future!

+5
source share
1 answer

If you use the gcloud command line tool to deploy your function, it will load all 1 files in your local directory, so any normal Node.js include / require execution method should work.

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

File layout

 ./ ../ 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 beta functions deploy helloWorld --stage-bucket=<bucket> --trigger-http 

Note

1 Currently, gcloud will not load the npm_modules/ directory unless you specify --include-ignored-files (see gcloud docs )

+3
source

Source: https://habr.com/ru/post/1264928/


All Articles