9

我想从我的云函数中调用其他 Google API,例如,在收到来自 Pubsub 的消息后将文件写入云存储。我怎样才能做到这一点?

4

1 回答 1

12

您可以使用Node.js 的 google-cloud 客户端库来完成此操作。相同的库也可用于 Java、Python 和 Ruby。

例如,在 Node JS 中,您需要相应地编辑您的 package.json 文件:

{
  "dependencies": {
    "google-cloud": "*"
  },
  ...
}

然后,在您的代码中,您可以简单地调用相关库。以下示例仅列出项目中的存储桶:

var gcloud = require('google-cloud');

exports.helloworld = function(context, data) {
  var gcs = gcloud.storage({projectId: '<PROJECT>'});    
  gcs.getBuckets(function(err, buckets) {
    if (!err) {
      buckets.forEach(function(bucket) {
        console.log(bucket.name);
      });
    } else {
      console.log('error: ' + err);
    }
  });

  context.success();
}

您也不应该包含整个google-cloudnpm 模块,而是指定一个特定的子模块,例如require('@google-cloud/storage')在上面的示例中。

于 2016-02-11T22:40:46.953 回答