npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

microservice-nats-comm

v1.0.1

Published

A communications package for microservices using Express.js and NATS Streaming

Downloads

148

Readme

microservice-nats-comm

microservice-nats-comm is an easy-to-use communication package that simplifies message publishing and subscribing between microservices using Express.js and NATS Streaming. It abstracts the complexity of connecting to and interacting with a NATS Streaming server, enabling smooth communication in a microservices architecture. Installation

Install the package using npm:


npm install microservice-nats-comm

Features

Publish messages to any NATS Streaming subject.
Subscribe to subjects and handle incoming messages.
Automatic connection and error handling for NATS Streaming.

Usage

Below are examples showing how to use this package in two microservices: one that publishes messages, and another that subscribes to them.

1. Publisher Microservice

The publisher microservice sends messages to a specific subject. Example Setup

const express = require('express');
const NATSClient = require('microservice-nats-comm');

const app = express();
const port = 3000;

// Create a NATS client instance
const natsClient = new NATSClient('test-cluster', 'publisher-microservice');

// Connect to NATS and publish a message on request
natsClient.connect().then(() => {
    console.log('Connected to NATS as Publisher.');

    // Publish a message when the /publish route is called
    app.post('/publish', (req, res) => {
        const message = 'Hello from Publisher to Subscriber!';

        natsClient.publish('event-channel', message)
            .then((guid) => {
                console.log(`Message published with GUID: ${guid}`);
                res.status(200).send(`Message published: ${message}`);
            })
            .catch(err => {
                console.error('Error publishing message:', err);
                res.status(500).send('Failed to publish message');
            });
    });
}).catch(err => {
    console.error('Failed to connect to NATS:', err);
});

app.listen(port, () => {
    console.log(`Publisher microservice running at http://localhost:${port}`);
}); 

2. Subscriber Microservice

The subscriber microservice listens to a subject and processes incoming messages. Example Setup


const express = require('express');
const NATSClient = require('microservice-nats-comm');

const app = express();
const port = 3001;

// Create a NATS client instance
const natsClient = new NATSClient('test-cluster', 'subscriber-microservice');

// Connect to NATS and subscribe to the 'event-channel'
natsClient.connect().then(() => {
    console.log('Connected to NATS as Subscriber.');

    // Subscribe to the subject 'event-channel'
    natsClient.subscribe('event-channel', (msg) => {
        const message = msg.getData();
        console.log(`Message received: ${message}`);
    });
}).catch(err => {
    console.error('Failed to connect to NATS:', err);
});

app.listen(port, () => {
    console.log(`Subscriber microservice running at http://localhost:${port}`);
});

Configuration

When creating a NATSClient instance, you must pass three parameters:

clusterId: The NATS Streaming cluster ID.
clientId: A unique client ID for each microservice (should differ between Publisher and Subscriber).
natsUrl (optional): The URL of the NATS Streaming server. If not provided, it defaults to nats://localhost:4222.

javascript


const natsClient = new NATSClient(clusterId, clientId, [natsUrl]);

    clusterId: The NATS cluster identifier (e.g., 'test-cluster').
    clientId: The unique client identifier for the microservice (e.g., 'publisher-microservice' or 'subscriber-microservice').
    natsUrl (optional): The URL to the NATS Streaming server (default: 'nats://localhost:4222').

API

The package provides the following methods:
connect()

Connects to the NATS Streaming server and returns a Promise that resolves when the connection is established.

natsClient.connect().then(() => {
    console.log('Connected to NATS');
}).catch(err => {
    console.error('Error connecting to NATS:', err);
});

publish(subject, message) Publishes a message to the specified subject.

subject: The name of the NATS subject/channel.
message: The message content to be published.
natsClient.publish('event-channel', 'Hello from Publisher!')
    .then((guid) => {
        console.log(`Message published with GUID: ${guid}`);
    })
    .catch(err => {
        console.error('Error publishing message:', err);
    });

subscribe(subject, callback)

Subscribes to a subject and listens for messages. The callback function will be called whenever a new message is received.

subject: The name of the NATS subject/channel.
callback: A function that takes a message object as its argument.
natsClient.subscribe('event-channel', (msg) => {
    console.log(`Message received: ${msg.getData()}`);
});

disconnect()

Closes the connection to NATS Streaming.

natsClient.disconnect();
console.log('Disconnected from NATS');

Error Handling

You can catch connection and publishing errors by using Promises or try-catch in an async/await setup:

natsClient.connect().catch((err) => {
    console.error('Failed to connect to NATS:', err);
});

Example with Environment Variables

You can configure the connection parameters using environment variables for flexibility:

Create a .env file in your microservice directories:

NATS_CLUSTER_ID=test-cluster
NATS_CLIENT_ID=publisher-microservice
NATS_URL=nats://localhost:4222

Load the variables and use them in your code:

require('dotenv').config();
const NATSClient = require('microservice-nats-comm');

const natsClient = new NATSClient(process.env.NATS_CLUSTER_ID, process.env.NATS_CLIENT_ID, process.env.NATS_URL);

License

This package is licensed under ISC. See the LICENSE file for more details.