node.js - 如何解析从Pub/sub触发的Cloud Function中的Json负载

标签 node.js google-cloud-functions google-cloud-pubsub

我是谷歌云功能和 Node Js 的新手,当我尝试解析 Json 负载时,不断收到此错误

exports.processdata = (event, context) => {

  const pubsubMessage = event;

 var obj = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());
console.log(obj.temp);


};

错误

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
Function.Buffer.from

CLoud 函数在 Node.Js 版本 8 上运行

最佳答案

您可以使用属性.json读取json负载,下面是完整的代码

const functions = require('firebase-functions');
exports.processdata = functions.pubsub.topic('topic-np').onPublish((message) => {
  // [START readJson]
  // Get the `name` attribute of the PubSub message JSON body.
  let name = null;
  try {
    name = message.json.name;
  } catch (e) {
    console.error('PubSub message was not JSON', e);
  }

引用:https://firebase.google.com/docs/functions/pubsub-events

如果您正在测试在 Pub/Sub 上触发的云函数,请在主题中发布消息,然后通过云函数中的日志进行验证。

关于node.js - 如何解析从Pub/sub触发的Cloud Function中的Json负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59942704/

相关文章:

node.js - Firebase 函数(用 NodeJS 编写)在从实时数据库中删除对象时从云存储中删除文件

javascript - 部署 firebase 云函数时出现意外错误

go - 如何使用个人(gcloud)凭据发布到PubSub

javascript - 将服务器发送的事件与 Express 一起使用

javascript - 使用 require vs fs.readFile 读取 json 文件内容

javascript - 如何从可调用的 https 云函数将文件上传到 Firebase Storage

gmail-api - setIamPolicy 的 Gmail 通知问题

google-cloud-platform - 无法使用服务帐户订阅 google pub 子主题

javascript - node.js mongodb - collection.find().toArray(callback) 返回空

node.js - Sequelize 一对多查询(包含)产生 Y 与 X 无关