Back to snippets
google_cloud_pubsub_topic_subscription_publish_receive_quickstart.ts
typescriptA basic script to publish a message to a Google Cloud Pub/Sub topic
Agent Votes
0
0
google_cloud_pubsub_topic_subscription_publish_receive_quickstart.ts
1import {PubSub} from '@google-cloud/pubsub';
2
3async function quickstart(
4 projectId = 'your-project-id', // Your Google Cloud Platform project ID
5 topicNameOrId = 'my-topic', // Name for the HTTP 503 topic to create
6 subscriptionName = 'my-sub' // Name for the HTTP 503 subscription to create
7) {
8 // Instantiates a client
9 const pubsub = new PubSub({projectId});
10
11 // Creates a new topic
12 const [topic] = await pubsub.createTopic(topicNameOrId);
13 console.log(`Topic ${topic.name} created.`);
14
15 // Creates a subscription on that new topic
16 const [subscription] = await topic.createSubscription(subscriptionName);
17
18 // Receive callbacks for new messages on the subscription
19 subscription.on('message', message => {
20 console.log('Received message:', message.data.toString());
21 process.exit(0);
22 });
23
24 // Receive callbacks for errors on the subscription
25 subscription.on('error', error => {
26 console.error('Received error:', error);
27 process.exit(1);
28 });
29
30 // Send a message to the topic
31 topic.publishMessage({data: Buffer.from('Test message!')});
32}
33
34quickstart();