To get started with Cloud Pub/Sub in Node.js, follow these steps to set up your environment, install the library, and run a basic publish/subscribe flow.
1. Prerequisites
- Select or create a Google Cloud Platform project.
- Enable billing for your project.
- Enable the Google Cloud Pub/Sub API.
- Set up authentication to allow your local workstation to access the API.
2. Installation
Install the client library using npm:
npm install @google-cloud/pubsub
3. Basic Usage Example
The following example demonstrates how to instantiate a client, create a topic, create a subscription, listen for messages, and publish a message.
// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');
async function quickstart(
projectId = 'your-project-id', // Your Google Cloud Platform project ID
topicNameOrId = 'my-topic', // Name for the new topic to create
subscriptionName = 'my-sub', // Name for the new subscription to create
) {
// Instantiates a client
const pubsub = new PubSub({projectId});
// Creates a new topic
const [topic] = await pubsub.createTopic(topicNameOrId);
console.log(`Topic ${topic.name} created.`);
// Creates a subscription on that new topic
const [subscription] = await topic.createSubscription(subscriptionName);
// Receive callbacks for new messages on the subscription
subscription.on('message', message => {
console.log('Received message:', message.data.toString());
process.exit(0);
});
// Receive callbacks for errors on the subscription
subscription.on('error', error => {
console.error('Received error:', error);
process.exit(1);
});
// Send a message to the topic
await topic.publishMessage({data: Buffer.from('Test message!')});
}