The default export of the @google-cloud/pubsub
package is the
PubSub class.
See PubSub and ClientConfig for client methods and configuration options.
Examples
Install the client library with <a href="https://www.npmjs.com/">npm</a>:
```
npm install @google-cloud/pubsub
```
Import the client library
```
const {PubSub} = require('@google-cloud/pubsub');
```
Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>:
```
const pubsub = new PubSub();
```
Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>:
```
const pubsub = new PubSub({
projectId: 'your-project-id',
keyFilename: '/path/to/keyfile.json'
});
```
// Imports the Google Cloud client library
import {PubSub} from '@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
topic.publishMessage({data: Buffer.from('Test message!')});
}
Members
v1
Reference to internal generated clients, advanced use only.
Properties:
Name | Type | Description |
---|---|---|
PublisherClient |
constructor |
Reference to v1.PublisherClient. |
SubscriberClient |
constructor |
Reference to v1.SubscriberClient. |