gpt4 book ai didi

node.js - NodeJS 和 GCP PubSub - 类型错误 : PubSub is not a constructor at Object. <匿名>

转载 作者:行者123 更新时间:2023-12-04 10:36:50 26 4
gpt4 key购买 nike

我正在学习 https://www.woolha.com/tutorials/node-js-google-cloud-pub-sub-basic-examples 上的教程并且有一些困难..

我在 server.js 中有以下代码:-

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');


const dotenv = require('dotenv');
dotenv.config(); // Reads the .env file from the local folder.

// PubSub constant initialisation
const PubSub = require(`@google-cloud/pubsub`);
const pubsub = new PubSub();
const data = new Date().toString();
const dataBuffer = Buffer.from(data);
const topicName = 'sensehat-led-config';


app.use(bodyParser.urlencoded({ extended: true}));

// Tell the app to use the public folder.
app.use(express.static('public'));

app.get('/', (req,res) => {
res.send('Hello from App Engine!');
})

app.get('/submit', (req, res) => {
res.sendFile(path.join(__dirname, '/views/form.html'));
})

// Need to figure out how to get the css file to work in this. Can't be that hard.
app.get('/sensehat', (req, res) => {
res.sendFile(path.join(__dirname, '/views/sensehat.html'));
})


app.get('/sensehat-publish-message', (req, res) =>{
pubsub
.topic(topicName)
.publisher()
.publish(dataBuffer)
.then(messageId => {
console.log(`Message ${messageId} published`);
})
.catch(err => {
console.error('ERROR:', err);
});
})


app.post('/submit', (req, res) => {
console.log({
name: req.body.name,
message: req.body.message
});
res.send('Thanks for your message!');
})

// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log('Server listening on port ${PORT}...');
})

但是当我运行它时,我得到了一个“500 服务器错误”,并且查看 Stackdriver 日志我得到了以下错误:-

TypeError: PubSub is not a constructor at Object.<anonymous>

我绝对是 NodeJS 的新手并且摸索着自己的路。阅读后,我认为问题出在

const PubSub = require(`@google-cloud/pubsub`);
const pubsub = new PubSub();

行,但不知道如何纠正。

最佳答案

您可以尝试使用所有库的最新版本。package.json 中的依赖

"dependencies": {
"@google-cloud/pubsub": "1.5.0",
"google-gax": "1.14.1",
"googleapis": "47.0.0"
}

示例代码-

const {
PubSub
} = require('@google-cloud/pubsub');

const pubsub = new PubSub({
projectId: process.env.PROJECT_ID
});

module.exports = {
publishToTopic: function(topicName, data) {
return pubsub.topic(topicName).publish(Buffer.from(JSON.stringify(data)));
},
};

调用文件代码

const PubSubPublish = require('path to your above file')
let publishResult = await PubSubPublish.publishToTopic(process.env.TOPIC_NAME, data)

希望对您有所帮助!

关于node.js - NodeJS 和 GCP PubSub - 类型错误 : PubSub is not a constructor at Object. <匿名>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60136446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com