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) { const { PubSub } = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const subscription = pubsub.subscription(subscriptionName);
let messageCount = 0; const messageHandler = message => { console.log(`Received message ${message.id}:`); console.log(`\tData: ${message.data}`); console.log(`\tAttributes: ${message.attributes}`); messageCount += 1;
message.ack(); };
subscription.on(`message`, messageHandler);
setTimeout(() => { subscription.removeListener('message', messageHandler); console.log(`${messageCount} message(s) received.`); }, timeout * 1000); } listenForMessages('my-topic-Subscription', 3);
|