-
Notifications
You must be signed in to change notification settings - Fork 0
/
PullMessage.js
41 lines (34 loc) · 1.34 KB
/
PullMessage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function listenForMessages(subscriptionName, timeout) {
// [START pubsub_subscriber_async_pull]
// [START pubsub_quickstart_subscriber]
// Imports the Google Cloud client library
const { PubSub } = require('@google-cloud/pubsub');
// Creates a client
const pubsub = new PubSub();
/**
* TODO(developer): Uncomment the following lines to run the sample.
*/
// const subscriptionName = 'my-sub';
// const timeout = 60;
// References an existing subscription
const subscription = pubsub.subscription(subscriptionName);
// Create an event handler to handle messages
let messageCount = 0;
const messageHandler = message => {
console.log(`Received message ${message.id}:`);
console.log(`\tData: ${message.data}`);
console.log(`\tAttributes: ${message.attributes}`);
messageCount += 1;
// "Ack" (acknowledge receipt of) the message
message.ack();
};
// Listen for new messages until timeout is hit
subscription.on(`message`, messageHandler);
setTimeout(() => {
subscription.removeListener('message', messageHandler);
console.log(`${messageCount} message(s) received.`);
}, timeout * 1000);
// [END pubsub_subscriber_async_pull]
// [END pubsub_quickstart_subscriber]
}
listenForMessages('my-topic-Subscription', 3);