Constructor

PubSub

new PubSub(options)

Cloud Pub/Sub is a reliable, many-to-many, asynchronous messaging service from Cloud Platform.

Parameter

options

Optional

ClientConfig

Configuration options.

See also

Cloud Pub/Sub overview

Examples

Import the client library

const PubSub = require('@google-cloud/pubsub');

Create a client that uses Application Default Credentials (ADC):

const pubsub = new PubSub();

Create a client with explicit credentials:

const pubsub = new PubSub({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json'
});

Full quickstart example:

// Imports the Google Cloud client library
const PubSub = require('@google-cloud/pubsub');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const pubsubClient = new PubSub({
  projectId: projectId,
});

// The name for the new topic
const topicName = 'my-new-topic';

// Creates the new topic
pubsubClient
  .createTopic(topicName)
  .then(results => {
    const topic = results[0];
    console.log(`Topic ${topic.name} created.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Properties

v1

static

object

Properties

Parameter

PublisherClient

constructor

Reference to v1.PublisherClient.

SubscriberClient

constructor

Reference to v1.SubscriberClient.

See also
v1.PublisherClient
v1.SubscriberClient

isEmulator

boolean

Methods

createSubscription

createSubscription(topic, name, options, callback) returns Promise containing CreateSubscriptionResponse

Create a subscription to a topic.

Parameter

topic

(Topic or string)

The Topic to create a subscription to.

name

string

The name of the subscription.

options

Optional

CreateSubscriptionRequest

See a Subscription resource.

callback

Optional

CreateSubscriptionCallback

Callback function.

See also

Subscriptions: create API Documentation

Topic#createSubscription
Throws

Error 

If a Topic instance or topic name is not provided.

Error 

If a subscription name is not provided.

Returns

Promise containing CreateSubscriptionResponse 

Examples

Subscribe to a topic.

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = 'messageCenter';
const name = 'newMessages';

const callback = function(err, subscription, apiResponse) {};

pubsub.createSubscription(topic, name, callback);

If the callback is omitted, we'll return a Promise.

pubsub.createSubscription(topic, name).then(function(data) {
  const subscription = data[0];
  const apiResponse = data[1];
});

createTopic

createTopic(name, gaxOpts, callback) returns Promise containing CreateTopicResponse

Create a topic with the given name.

Parameter

name

string

Name of the topic.

gaxOpts

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.

callback

Optional

CreateTopicCallback

Callback function.

See also

Topics: create API Documentation

Returns

Promise containing CreateTopicResponse 

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.createTopic('my-new-topic', function(err, topic, apiResponse) {
  if (!err) {
    // The topic was created successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
pubsub.createTopic('my-new-topic').then(function(data) {
  const topic = data[0];
  const apiResponse = data[1];
});

getSnapshots

getSnapshots(query, callback) returns Promise containing GetSnapshotsResponse

Get a list of snapshots.

Parameter

query

Optional

GetSnapshotsRequest

Query object for listing snapshots.

callback

Optional

GetSnapshotsCallback

Callback function.

Returns

Promise containing GetSnapshotsResponse 

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.getSnapshots(function(err, snapshots) {
  if (!err) {
    // snapshots is an array of Snapshot objects.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
pubsub.getSnapshots().then(function(data) {
  const snapshots = data[0];
});

getSnapshotsStream

getSnapshotsStream(options) returns ReadableStream

Get a list of the Snapshot objects as a readable object stream.

Parameter

options

Optional

GetSnapshotsRequest

Configuration object. See PubSub#getSnapshots for a complete list of options.

Returns

ReadableStream 

A readable stream of Snapshot instances.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.getSnapshotsStream()
  .on('error', console.error)
  .on('data', function(snapshot) {
    // snapshot is a Snapshot object.
  })
  .on('end', function() {
    // All snapshots retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
pubsub.getSnapshotsStream()
  .on('data', function(snapshot) {
    this.end();
  });

getSubscriptions

getSubscriptions(query, callback) returns Promise containing GetSubscriptionsResponse

Get a list of the subscriptions registered to all of your project's topics. You may optionally provide a query object as the first argument to customize the response.

Your provided callback will be invoked with an error object if an API error occurred or an array of Subscription objects.

To get subscriptions for a topic, see Topic.

Parameter

query

Optional

GetSubscriptionsRequest

Query object for listing subscriptions.

callback

Optional

GetSubscriptionsCallback

Callback function.

See also

Subscriptions: list API Documentation

Returns

Promise containing GetSubscriptionsResponse 

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.getSubscriptions(function(err, subscriptions) {
  if (!err) {
    // subscriptions is an array of Subscription objects.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
pubsub.getSubscriptions().then(function(data) {
  const subscriptions = data[0];
});

getSubscriptionsStream

getSubscriptionsStream(options) returns ReadableStream

Get a list of the {module:pubsub/subscription} objects registered to this topic as a readable object stream.

Parameter

options

Optional

GetSubscriptionsRequest

Configuration object. See PubSub#getSubscriptions for a complete list of options.

Returns

ReadableStream 

A readable stream of Subscription instances.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.getSubscriptionsStream()
  .on('error', console.error)
  .on('data', function(subscription) {
    // subscription is a Subscription object.
  })
  .on('end', function() {
    // All subscriptions retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
topic.getSubscriptionsStream()
  .on('data', function(subscription) {
    this.end();
  });

getSubscriptionsStream

getSubscriptionsStream(options) returns ReadableStream

Get a list of the Subscription objects registered to all of your project's topics as a readable object stream.

Parameter

options

Optional

GetSubscriptionsRequest

Configuration object. See PubSub#getSubscriptions for a complete list of options.

Returns

ReadableStream 

A readable stream of Subscription instances.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.getSubscriptionsStream()
  .on('error', console.error)
  .on('data', function(subscription) {
    // subscription is a Subscription object.
  })
  .on('end', function() {
    // All subscriptions retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
pubsub.getSubscriptionsStream()
  .on('data', function(subscription) {
    this.end();
  });

getTopics

getTopics(query, callback) returns Promise containing GetTopicsResponse

Get a list of the topics registered to your project. You may optionally provide a query object as the first argument to customize the response.

Parameter

query

Optional

GetTopicsRequest

Query object for listing topics.

callback

Optional

GetTopicsCallback

Callback function.

See also

Topics: list API Documentation

Returns

Promise containing GetTopicsResponse 

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.getTopics(function(err, topics) {
  if (!err) {
    // topics is an array of Topic objects.
  }
});

//-
// Customize the query.
//-
pubsub.getTopics({
  pageSize: 3
}, function(err, topics) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
pubsub.getTopics().then(function(data) {
  const topics = data[0];
});

getTopicsStream

getTopicsStream(options) returns ReadableStream

Get a list of the {module:pubsub/topic} objects registered to your project as a readable object stream.

Parameter

options

Optional

GetTopicsRequest

Configuration object. See PubSub#getTopics for a complete list of options.

Returns

ReadableStream 

A readable stream of Topic instances.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

pubsub.getTopicsStream()
  .on('error', console.error)
  .on('data', function(topic) {
    // topic is a Topic object.
  })
  .on('end', function() {
    // All topics retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
pubsub.getTopicsStream()
  .on('data', function(topic) {
    this.end();
  });

snapshot

snapshot(name) returns Snapshot

Create a Snapshot object. See Subscription#createSnapshot to create a snapshot.

Parameter

name

string

The name of the snapshot.

Throws

Error 

If a name is not provided.

Returns

Snapshot 

A Snapshot instance.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const snapshot = pubsub.snapshot('my-snapshot');

subscription

subscription(name, options) returns Subscription

Create a Subscription object. This command by itself will not run any API requests. You will receive a Subscription object, which will allow you to interact with a subscription.

Parameter

name

string

Name of the subscription.

options

Optional

object

Configuration object.

Values in options have the following properties:

Parameter

flowControl

object

Flow control configurations for receiving messages. Note that these options do not persist across subscription instances.

flowControl.maxBytes

number

The maximum number of bytes in un-acked messages to allow before the subscription pauses incoming messages. Defaults to 20% of free memory.

flowControl.maxMessages

number

The maximum number of un-acked messages to allow before the subscription pauses incoming messages. Default: Infinity.

maxConnections

number

Use this to limit the number of connections to be used when sending and receiving messages. Default: 5.

Throws

Error 

If subscription name is omitted.

Returns

Subscription 

A Subscription instance.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const subscription = pubsub.subscription('my-subscription');

// Register a listener for `message` events.
subscription.on('message', function(message) {
  // Called every time a message is received.
  // message.id = ID of the message.
  // message.ackId = ID used to acknowledge the message receival.
  // message.data = Contents of the message.
  // message.attributes = Attributes of the message.
  // message.publishTime = Timestamp when Pub/Sub received the message.
});

topic

topic(name) returns Topic

Create a Topic object. See PubSub#createTopic to create a topic.

Parameter

name

string

The name of the topic.

Throws

Error 

If a name is not provided.

Returns

Topic 

A Topic instance.

Example

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');