Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS & GCP PubSub - TypeError: PubSub is not a constructor at Object.<anonymous>

I'm following a tutorial at https://www.woolha.com/tutorials/node-js-google-cloud-pub-sub-basic-examples and having some difficulty..

I've the following code in 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}...');
})

But when I run it I get a '500 Server Error', and looking at the Stackdriver logs I get the following error:-

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

I'm definitely a newbie at NodeJS and feeling my way around. After reading around I think the issue is coming from the

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

lines, but no idea how to rectify this.

like image 462
Mat Richardson Avatar asked Sep 14 '25 05:09

Mat Richardson


1 Answers

You can try with latest versions of all libraries. Dependencies in package.json

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

Example code -

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)));
  },
};

Calling file code

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

Hope it helps!

like image 79
SaharshJ Avatar answered Sep 15 '25 18:09

SaharshJ