You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

node-consul-service

Package Overview
Dependencies
Maintainers
0
Versions
68
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

node-consul-service

A robust Node.js service that integrates with HashiCorp Consul for service discovery and configuration management. This service provides a comprehensive solution for managing distributed systems and microservices architecture, making it easier to handle s

1.0.67
latest
Source
npmnpm
Version published
Weekly downloads
750
6150%
Maintainers
0
Weekly downloads
 
Created
Source

Node Consul Service

A robust Node.js service that integrates with HashiCorp Consul for service discovery and configuration management. This service provides a comprehensive solution for managing distributed systems and microservices architecture, making it easier to handle service communication, health checks, and configuration management in a distributed environment.

Table of Contents

  • Features
  • Prerequisites
  • Installation
  • Initialization
  • API Documentation
  • Examples
  • Contributing
  • License

Features

  • Service Registration & Discovery: Automatically register and discover services in your distributed system
  • Health Checking: Built-in health check mechanisms for service monitoring
  • Service Communication: Simplified inter-service communication with automatic load balancing
  • Service Instance Management: Easy management of multiple service instances
  • Data Linking: Efficient data aggregation and linking across services
  • Caching Support: Optional caching mechanism for improved performance

Prerequisites

  • Node.js (v14 or higher)
  • HashiCorp Consul server
  • npm or yarn package manager

Installation

# Using npm
npm install node-consul-service

# Using yarn
yarn add node-consul-service

Initialization

Service Initialization

Before using any functions from the library, you must initialize the client first. You can initialize the client by passing configuration options:

const { initClient } = require('node-consul-service');

await initClient({
  host: 'localhost',
  port: 8500,
  secure: false,
  token: 'your-token',           // Optional
  datacenter: 'dc1',            // Optional
  retryAttempts: 3,             // Number of connection retry attempts
  retryDelay: 1000              // Delay between retries in milliseconds
});

Initialization Features

  • Automatic Retry: Attempts to connect multiple times on failure
  • Connection Verification: Verifies successful connection before proceeding
  • State Management: Tracks initialization state to prevent multiple initializations
  • Error Handling: Clear and helpful error messages

Complete Usage Example

const { initClient, registerService } = require('node-consul-service');

async function startService() {
  try {
    // Initialize client
    await initClient({
      host: 'localhost',
      port: 8500,
      retryAttempts: 3
    });

    // Register service
    await registerService({
      name: 'my-service',
      id: 'my-service-1',
      port: 3000
    });

    console.log('✅ Service started successfully');
  } catch (error) {
    console.error('❌ Failed to start service:', error);
    process.exit(1);
  }
}

startService();

API Documentation

Core Functions

Service Registration

const { registerService } = require('node-consul-service');

await registerService({
  name: 'service-name',
  id: 'service-id',
  port: 3000,
  address: 'localhost',
  check: {
    name: 'service health check',
    http: 'http://localhost:3000/health',
    interval: '10s',
    timeout: '5s',
    deregistercriticalserviceafter: '1m'
  }
});

Service Communication

const { callService } = require('node-consul-service');

// Simple GET request
const result = await callService('service-name', '/endpoint');

// POST request with data
const response = await callService('service-name', {
  method: 'POST',
  path: '/endpoint',
  data: { key: 'value' }
});

Service Discovery

const { 
  listServices,
  getServiceInstances,
  getRandomServiceInstance 
} = require('node-consul-service');

// List all registered services
const services = await listServices();

// Get all instances of a specific service
const instances = await getServiceInstances('service-name');

// Get a random instance of a service
const instance = await getRandomServiceInstance('service-name');

Data Linking

The dataLink function provides a powerful way to aggregate and link data from multiple services efficiently.

const { dataLink } = require('node-consul-service');

const data = [
  { userId: '123', name: 'John' },
  { userId: '456', name: 'Jane' }
];

const schema = [
  {
    Field: 'userId',           // Field name in the original data
    service: 'user-service',   // Target service name
    path: '/api/users/batch',  // API endpoint path
    cacheGetter: async (ids) => {
      // Optional function to get data from cache
      return await cache.getUsers(ids);
    }
  }
];

const result = await dataLink(data, schema);

Schema Properties

  • Field: Field name in the original data that contains the identifier
  • service: Name of the service to be called
  • path: API endpoint path in the target service
  • cacheGetter: Optional function to get data from cache before calling the service

Examples

Basic Service Setup

const { registerService, callService } = require('node-consul-service');

// Register your service
await registerService({
  name: 'my-service',
  id: 'my-service-1',
  port: 3000,
  address: 'localhost',
  check: {
    http: 'http://localhost:3000/health',
    interval: '10s'
  }
});

// Call another service
const response = await callService('other-service', '/api/data');

Advanced Data Linking

const { dataLink } = require('node-consul-service');

// Complex data linking example
const orders = [
  { orderId: '1', userId: '123', productId: 'P1' },
  { orderId: '2', userId: '456', productId: 'P2' }
];

const schema = [
  {
    Field: 'userId',
    service: 'user-service',
    path: '/api/users/batch'
  },
  {
    Field: 'productId',
    service: 'product-service',
    path: '/api/products/batch'
  }
];

const enrichedOrders = await dataLink(orders, schema);

Contributing

We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  • Fork the repository
  • Create your feature branch (git checkout -b feature/amazing-feature)
  • Commit your changes (git commit -m 'Add some amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Keywords

consul

FAQs

Package last updated on 29 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts