How to Use Pub/Sub with Node.js on Google Cloud
To use
Pub/Sub with Node.js, install the @google-cloud/pubsub package, create a client, then publish and subscribe to messages using the client methods. This lets your Node.js app send messages to topics and receive them from subscriptions asynchronously.Syntax
Here is the basic syntax to publish and subscribe messages using the @google-cloud/pubsub library in Node.js.
- Import and create client: Initialize PubSub client to interact with the service.
- Publish message: Use
topic.publishMessage()to send data. - Subscribe to messages: Use
subscription.on('message')to receive messages.
javascript
const {PubSub} = require('@google-cloud/pubsub'); const pubsub = new PubSub(); // Publish a message async function publishMessage(topicName, data) { const dataBuffer = Buffer.from(data); await pubsub.topic(topicName).publishMessage({data: dataBuffer}); console.log(`Message published to ${topicName}`); } // Listen for messages function listenForMessages(subscriptionName) { const subscription = pubsub.subscription(subscriptionName); subscription.on('message', message => { console.log(`Received message: ${message.data.toString()}`); message.ack(); }); }
Example
This example shows how to publish a message to a topic and listen for messages on a subscription using Node.js and Google Cloud Pub/Sub.
javascript
const {PubSub} = require('@google-cloud/pubsub'); const pubsub = new PubSub(); const topicName = 'my-topic'; const subscriptionName = 'my-subscription'; async function publishMessage() { const data = 'Hello, Pub/Sub!'; const dataBuffer = Buffer.from(data); await pubsub.topic(topicName).publishMessage({data: dataBuffer}); console.log(`Message published: ${data}`); } function listenForMessages() { const subscription = pubsub.subscription(subscriptionName); subscription.on('message', message => { console.log(`Received message: ${message.data.toString()}`); message.ack(); }); subscription.on('error', error => { console.error('Error receiving message:', error); }); } publishMessage(); listenForMessages();
Output
Message published: Hello, Pub/Sub!
Received message: Hello, Pub/Sub!
Common Pitfalls
Common mistakes when using Pub/Sub with Node.js include:
- Not acknowledging messages with
message.ack(), causing redelivery. - Using incorrect topic or subscription names.
- Not handling errors on subscriptions, which can crash the app.
- Publishing messages without converting data to a
Buffer.
Always check your Google Cloud permissions and ensure the Pub/Sub API is enabled.
javascript
/* Wrong: Not acknowledging message */ subscription.on('message', message => { console.log(`Received: ${message.data.toString()}`); // message.ack() missing here }); /* Right: Acknowledge message to prevent redelivery */ subscription.on('message', message => { console.log(`Received: ${message.data.toString()}`); message.ack(); });
Quick Reference
Remember these key points when using Pub/Sub with Node.js:
- Install the client library with
npm install @google-cloud/pubsub. - Use
Buffer.from()to convert message data before publishing. - Always acknowledge messages with
message.ack()after processing. - Handle errors on subscriptions to keep your app stable.
- Set environment variable
GOOGLE_APPLICATION_CREDENTIALSto your service account key file for authentication.
Key Takeaways
Install and import @google-cloud/pubsub to use Pub/Sub in Node.js.
Publish messages by converting data to Buffer and calling publishMessage on a topic.
Subscribe and listen for messages, always acknowledging them with message.ack().
Handle errors on subscriptions to avoid crashes.
Ensure correct permissions and environment setup for authentication.