在 HTTP 触发函数中发布主题
Publish on a topic in an HTTP triggered function
我在 GCP 中编写了一个 HTTP 触发函数,它按预期计算了一些数据,计算后,我想在 MQTT 主题上发布结果。
我添加了以下代码片段,但它触发了一个错误:
Error: Error: Cannot find module '@google-cloud/pubsub'
下面是添加的代码
//decoding worked
const PubSub = require('@google-cloud/pubsub');
// Your Google Cloud Platform project ID
const projectId = 'XXXXX';
// Instantiates a client
const pubsubClient = new PubSub({
projectId: projectId
});
// The name for the new topic
const topicName = 'XXXX';
// Creates the new topic
pubsubClient
.createTopic(topicName)
.then(results => {
const topic = results[0];
console.log(`Topic ${topic.name} created.`);
})
.catch(err => {
console.error('ERROR:', err);
});
如果我去掉库的导入,我得到
Error: ReferenceError: PubSub is not defined
那么 - 如何在 gcp 中通过 HTTP 触发函数在主题中发布?
您需要安装 @google-cloud/pubsub 库作为依赖项,以便您的 Cloud Functions 可以成功导入它。您可以通过 运行 在本地执行以下命令:
npm install --save @google-cloud/pubsub
这会将此库包含在您使用函数代码上传的 package.json 文件中。
如果您直接从开发者控制台编写函数,则需要将以下内容添加到 package.json 文件中:
"dependencies": {
"@google-cloud/pubsub": "^0.19.0"
}
我在 GCP 中编写了一个 HTTP 触发函数,它按预期计算了一些数据,计算后,我想在 MQTT 主题上发布结果。 我添加了以下代码片段,但它触发了一个错误:
Error: Error: Cannot find module '@google-cloud/pubsub'
下面是添加的代码
//decoding worked
const PubSub = require('@google-cloud/pubsub');
// Your Google Cloud Platform project ID
const projectId = 'XXXXX';
// Instantiates a client
const pubsubClient = new PubSub({
projectId: projectId
});
// The name for the new topic
const topicName = 'XXXX';
// Creates the new topic
pubsubClient
.createTopic(topicName)
.then(results => {
const topic = results[0];
console.log(`Topic ${topic.name} created.`);
})
.catch(err => {
console.error('ERROR:', err);
});
如果我去掉库的导入,我得到
Error: ReferenceError: PubSub is not defined
那么 - 如何在 gcp 中通过 HTTP 触发函数在主题中发布?
您需要安装 @google-cloud/pubsub 库作为依赖项,以便您的 Cloud Functions 可以成功导入它。您可以通过 运行 在本地执行以下命令:
npm install --save @google-cloud/pubsub
这会将此库包含在您使用函数代码上传的 package.json 文件中。
如果您直接从开发者控制台编写函数,则需要将以下内容添加到 package.json 文件中:
"dependencies": {
"@google-cloud/pubsub": "^0.19.0"
}