Google Cloud Functions include private library

后端 未结 1 1048
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 00:05

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 Clo

相关标签:
1条回答
  • 2021-02-06 00:29

    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.

    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.

    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 functions deploy helloWorld --trigger-http
    

    Note

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

    0 讨论(0)
提交回复
热议问题