What is @google-cloud/pubsub?
The @google-cloud/pubsub npm package is a client library for accessing Google Cloud Pub/Sub, a fully-managed real-time messaging service that allows you to send and receive messages between independent applications. This package provides an easy-to-use API to interact with Google Cloud Pub/Sub and is designed to handle the complexities of the underlying API operations.
What are @google-cloud/pubsub's main functionalities?
Publishing Messages
This feature allows you to publish messages to a topic. The code sample demonstrates how to create a PubSub client, get a reference to a topic, and publish a message to that topic.
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topic = pubsub.topic('my-topic');
const messageBuffer = Buffer.from('Hello, world!');
topic.publish(messageBuffer);
Subscribing to Topics
This feature enables you to subscribe to a topic and receive messages. The code sample shows how to create a PubSub client, get a reference to a subscription, and set up an event handler to process received messages.
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const subscription = pubsub.subscription('my-subscription');
subscription.on('message', message => {
console.log('Received message:', message.data.toString());
message.ack();
});
Managing Topics and Subscriptions
This feature covers the management of topics and subscriptions, including creating and deleting them. The code sample illustrates how to create a new topic and delete an existing subscription.
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
// Create a new topic
pubsub.createTopic('new-topic').then(response => {
console.log('Topic created:', response[0].name);
});
// Delete a subscription
pubsub.subscription('old-subscription').delete();
Other packages similar to @google-cloud/pubsub
aws-sdk
The AWS SDK for JavaScript provides a similar messaging service through Amazon SNS (Simple Notification Service) and SQS (Simple Queue Service). While AWS SDK supports both pub/sub and queue-based messaging, @google-cloud/pubsub is specifically optimized for Google Cloud's Pub/Sub service.
azure-sb
Azure-sb is a client library for Azure Service Bus, which also supports pub/sub messaging patterns. Compared to @google-cloud/pubsub, azure-sb is tailored for integration with Azure's ecosystem and supports additional features like message sessions and dead-letter queues.
rascal
Rascal is an abstraction layer over amqplib for RabbitMQ, a popular open-source message broker. Unlike @google-cloud/pubsub, which is a cloud-native service, Rascal with RabbitMQ can be used both on-premises and in the cloud, offering more flexibility in deployment models.
@google-cloud/pubsub
Google Cloud Pub/Sub Client Library for Node.js
Looking for more Google APIs than just Pub/Sub? You might want to check out google-cloud
.
$ npm install --save @google-cloud/pubsub
var pubsub = require('@google-cloud/pubsub')({
projectId: 'grape-spaceship-123',
keyFilename: '/path/to/keyfile.json'
});
var topic = pubsub.topic('my-topic');
topic.publish('New message!', function(err) {});
var options = {
reuseExisting: true
};
topic.subscribe('subscription-name', options, function(err, subscription) {
function onError(err) {}
function onMessage(message) {}
subscription.on('error', onError);
subscription.on('message', onMessage);
subscription.removeListener('message', onMessage);
subscription.removeListener('error', onError);
});
topic.publish('New message!').then(function(data) {
var messageIds = data[0];
});
var pubsub = require('@google-cloud/pubsub')({
promise: require('bluebird')
});
Authentication
It's incredibly easy to get authenticated and start using Google's APIs. You can set your credentials on a global basis as well as on a per-API basis. See each individual API section below to see how you can auth on a per-API-basis. This is useful if you want to use different accounts for different Google Cloud services.
On Google Compute Engine
If you are running this client on Google Compute Engine, we handle authentication for you with no configuration. You just need to make sure that when you set up the GCE instance, you add the correct scopes for the APIs you want to access.
var projectId = process.env.GCLOUD_PROJECT;
var pubsub = require('@google-cloud/pubsub')({
projectId: projectId
});
Elsewhere
If you are not running this client on Google Compute Engine, you need a Google Developers service account. To create a service account:
- Visit the Google Developers Console.
- Create a new project or click on an existing project.
- Navigate to APIs & auth > APIs section and turn on the following APIs (you may need to enable billing in order to use these services):
- Navigate to APIs & auth > Credentials and then:
- If you want to use a new service account, click on Create new Client ID and select Service account. After the account is created, you will be prompted to download the JSON key file that the library uses to authenticate your requests.
- If you want to generate a new key for an existing service account, click on Generate new JSON key and download the JSON key file.
var projectId = process.env.GCLOUD_PROJECT;
var pubsub = require('@google-cloud/pubsub')({
projectId: projectId,
keyFilename: '/path/to/keyfile.json'
credentials: require('./path/to/keyfile.json')
});