我有以下代码:

exports = function(changeEvent) {
  var {PubSub} = require("@google-cloud/pubsub");
  var avro = require("avro-js");
  const keyFilename = context.values.get("GOOGLE_APPLICATION_CREDENTIALS")
  const projectId = "<project_name>"
  const pubSubClient = new PubSub({projectId, keyFilename});
  const topicName = "<topic_name>"
  const topic = pubSubClient.topic(topicName);
  try {
    const data = "something";
    const dataBuffer = Buffer.from(data);
    return topic.publish(dataBuffer)
      .then((messageId) => console.log(`Message ${messageId} published.`))
      .catch((err) => console.log(`Error publishing message: ${err}`));
  } catch(err) {
    console.log("Error: ", err.message);
  }
};

运行上述命令时,它返回以下内容:

Error publishing message: FunctionError: TypeError: 'createReadStream' is not a function
> result: 
{
   "$undefined": true
}
> result (JavaScript): 
EJSON.parse('{"$undefined":true}')

需要指出的是:

  1. 我不是第一个遇到这个问题的人,但这两个帖子都没有得到太多关注
  2. The GOOGLE_APPLICATION_CREDENTIALS value ought to be a path to the secret called service-account.. it's a json of a service account key from GCP. What confuses me though is that if I console.log the path it prints out the secret as json and not the path to the secret enter image description here

在这一点上,我不确定它能是什么.起初,我认为这可能是异步和同步的问题.但我try 了这两种方法,结果都出现了相同的错误.另一个问题可能是与客户端的身份验证.但是错误消息并没有为我提供太多信息,在搜索createReadStream的时候,我找不到任何有用的东西.

推荐答案

这可能是身份验证问题.

GOOGLE_APPLICATION_CREDENTIALS环境变量通常需要指向JSON密钥文件的文件路径,而不是JSON内容本身.然而,在像MongoDB Atlas触发器这样的无服务器环境中,您可能无法以传统方式访问文件系统.

您可以将凭据作为对象直接传递:

const credentials = JSON.parse(context.values.get("GOOGLE_APPLICATION_CREDENTIALS_JSON"));
const pubSubClient = new PubSub({ projectId, credentials }); 

请在此处查看更多可以传递给PubSub客户端的ClientConfiger类型的参数.

这也可能有帮助:https://github.com/googleapis/nodejs-pubsub/issues/367

Node.js相关问答推荐

如何将Node.js与Nuxt.js一起使用?

JsonwebToken过期后如何注销和清除cookie?

如何在Angular jest测试中调用Nodejs的垃圾收集? node v20的测试速度慢且内存泄漏

如何从基于JSON的HTML/SCSS模板生成PDF?

Rails 7导入npm yaml包时出现404错误

如何获取需要加载cheerio的网站部分数据?

为什么后端开发需要单独的服务器?

如何在没有云功能的情况下使用 Google PubSub

从数据库读取数据并将其作为可下载的 zip 文件发送

使用Typescript 时我应该避免循环导入吗?

如何以编程方式检测nodejs中的调试模式?

如何使用 mocha.js 模拟用于单元测试的依赖类?

React Native ios build:找不到 node

如何使用 Node.js 将 base64 编码图像(字符串)直接上传到 Google Cloud Storage 存储桶?

TypeError:请求路径包含未转义的字符,我该如何解决这个问题

找不到在 docker compose 环境中运行的 node js 应用程序的模块

使用 gzip/deflate 压缩的简单 HTTP 请求

为什么 Node.js 没有原生 DOM?

如何调试 Gulp 任务?

react-native run-android 无法识别