NodeJS&GCP PubSub-TypeError:PubSub不是对象的构造函数。<匿名> [英] NodeJS & GCP PubSub - TypeError: PubSub is not a constructor at Object.<anonymous>

查看:0
本文介绍了NodeJS&GCP PubSub-TypeError:PubSub不是对象的构造函数。<匿名>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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 Server Error’,并且查看StackDRIVE日志,我得到以下错误:-

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)

希望能有所帮助!

这篇关于NodeJS&amp;GCP PubSub-TypeError:PubSub不是对象的构造函数。&lt;匿名&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆