Star ✨ on GitHub

NodeManager

API reference for the NodeManager class in Moonlink.js

NodeManager Class

The NodeManager class is responsible for managing Lavalink nodes in Moonlink.js. It provides methods for adding, removing, and retrieving nodes, as well as selecting the best node based on various criteria.

manager.nodes

Overview

Properties

Core properties of the NodeManager class.

Available Properties

PropertyTypeDescription
managerManagerReference to the Manager instance
cacheMap<string | number, Node>Map containing all nodes with their identifiers as keys

Node Configuration

Node Configuration Options

Options for configuring Lavalink nodes.

Available Options

OptionTypeRequiredDefaultDescription
hoststringYes-Hostname or IP address of the Lavalink server
portnumberYes-Port number of the Lavalink server (0-65535)
passwordstringNo"youshallnotpass"Password for the Lavalink server
securebooleanNofalseWhether to use SSL/TLS for the connection
identifierstringNoGenerated UUIDUnique identifier for the node
idnumberNo-An optional numeric identifier for the node. Primarily for internal tracking, not used for node retrieval.
retryAmountnumberNo5Number of reconnection attempts
retryDelaynumberNo30000Delay between reconnection attempts (ms)
regionsstring[]No[]Voice regions this node is optimal for
pathVersionstringNo"v4"Lavalink REST API version
sessionIdstringNoGeneratedSession ID for resuming connections

Methods

Methods

Available methods in the NodeManager class.

Available Methods

check

checkmethod

Check Node Configuration

Validates a node configuration object before adding it to the cache.

Parameters
noderequiredINode
The node configuration object to validate

Returns & Example

Returnsvoid — Throws an error if the configuration is invalid

// Validate node configuration
manager.nodes.check({
host: 'localhost',
port: 2333,
password: 'youshallnotpass'
});

::

init

initmethod

Initialize Nodes

Initializes all nodes in the cache by connecting them to their respective Lavalink servers.

Returns & Example

Returnsvoid

// Initialize all nodes
manager.nodes.init();

add

addmethod

Add Node

Adds a new node to the cache and initializes it.

Parameters
noderequiredINode
The node configuration object to add

Returns & Example

Returnsvoid

// Add a new node
manager.nodes.add({
identifier: 'US-Node',
host: 'us.lavalink.com',
port: 2333,
password: 'password',
secure: true,
regions: ['us', 'us-east']
});

remove

removemethod

Remove Node

Removes a node from the cache and destroys its connection.

Parameters
identifierrequiredstring
The identifier of the node to remove

Returns & Example

Returnsvoid

// Remove a node
manager.nodes.remove('US-Node');

get

getmethod

Get Node

Gets a node from the cache by its identifier.

Parameters
identifierrequiredstring | number
The identifier of the node to get

Returns & Example

ReturnsNode — The node instance (throws error if not found)

// Get a specific node
const node = manager.nodes.get('US-Node');

// Get default node (if only one exists)
const defaultNode = manager.nodes.get('default');

best

bestproperty

Get Best Node

Gets the node with the least number of players from all connected nodes.

Returns & Example

ReturnsNode — The node with the least number of players

// Get the best available node
const bestNode = manager.nodes.best;

sortByUsage

sortByUsagemethod

Sort By Usage

Gets a node based on the specified sorting criteria. Only considers connected nodes.

Parameters
sortTyperequiredTSortTypeNode
The criteria to sort nodes by

Returns & Example

ReturnsNode — The node that best matches the sorting criteriaSorting Types

TypeDescription
"players"Sort by total number of players
"playingPlayers"Sort by number of actively playing players
"memory"Sort by memory usage
"cpuLavalink"Sort by Lavalink process CPU usage
"cpuSystem"Sort by system CPU usage
"uptime"Sort by node uptime
"random"Select a random node
// Get node with least memory usage
const memoryNode = manager.nodes.sortByUsage('memory');

// Get node with least CPU usage
const cpuNode = manager.nodes.sortByUsage('cpuLavalink');

// Get random node
const randomNode = manager.nodes.sortByUsage('random');

::

Usage Examples

Basic Examples

Simple examples of using the NodeManager.

Basic Node Setup

const { Client } = require('discord.js');
const { Manager } = require('moonlink.js');

const client = new Client();

// Create Manager with nodes
const manager = new Manager({
  nodes: [
    {
      identifier: 'Main',
      host: 'localhost',
      port: 2333,
      password: 'youshallnotpass'
    },
    {
      identifier: 'Backup',
      host: 'backup.lavalink.com',
      port: 2333,
      password: 'secure',
      secure: true
    }
  ],
  sendPayload: (guildId, payload) => {
    const guild = client.guilds.cache.get(guildId);
    if (guild) guild.shard.send(payload);
  }
});

// Initialize nodes when client is ready
client.once('ready', () => {
  manager.init(client.user.id);
});

// Handle node events
manager.on('nodeConnect', (node) => {
  console.log(`Node ${node.identifier} connected`);
});

manager.on('nodeError', (node, error) => {
  console.error(`Node ${node.identifier} encountered an error:`, error);
});

Regional Node Setup

const manager = new Manager({
  nodes: [
    {
      identifier: 'US-Node',
      host: 'us.lavalink.com',
      port: 2333,
      password: 'password',
      regions: ['us', 'us-east', 'us-west']
    },
    {
      identifier: 'EU-Node',
      host: 'eu.lavalink.com',
      port: 2333,
      password: 'password',
      regions: ['eu', 'eu-west', 'eu-central']
    }
  ],
  options: {
    sortPlayersByRegion: true
  }
});

Node Management

// Add a new node dynamically
manager.nodes.add({
  identifier: 'Dynamic-Node',
  host: 'dynamic.lavalink.com',
  port: 2333,
  password: 'password'
});

// Remove a node
manager.nodes.remove('Dynamic-Node');

// Get the best node for a specific use case
const memoryNode = manager.nodes.sortByUsage('memory');
const cpuNode = manager.nodes.sortByUsage('cpuLavalink');
const randomNode = manager.nodes.sortByUsage('random');

Node Events

Events

Events emitted by the NodeManager through the Manager instance.

Available Events

EventParametersDescription
nodeConnect(node: Node)Emitted when a node connects
nodeDisconnect(node: Node)Emitted when a node disconnects
nodeError(node: Node, error: Error)Emitted when a node encounters an error
nodeReconnect(node: Node)Emitted when a node attempts to reconnect
nodeCreate(node: Node)Emitted when a new node is created
nodeDestroy(identifier: string)Emitted when a node is destroyed
debug(message: string)Emitted for debugging information
Example
// Handle node events
manager.on('nodeConnect', (node) => {
  console.log(`Node ${node.identifier} connected`);
});

manager.on('nodeError', (node, error) => {
  console.error(`Node ${node.identifier} error:`, error);
});

manager.on('nodeDisconnect', (node) => {
  console.log(`Node ${node.identifier} disconnected`);
});

manager.on('debug', (message) => {
  console.log('Debug:', message);
});