Star ✨ on GitHub

Node

API reference for the Node class in Moonlink.js

The Node class represents a connection to a Lavalink server. It manages the communication between your Discord bot and the Lavalink server, enabling audio playback.

Constructor

The Node constructor is not meant to be used directly

Nodes are automatically created by the Manager when you initialize it with node options.
// Don't use directly
// new Node(options, manager);

// Instead, configure nodes through the Manager
const manager = new Manager({
  nodes: [
    {
      identifier: 'Node 1',
      host: 'localhost',
      port: 2333,
      password: 'youshallnotpass',
      secure: false
    }
  ],
  // ... other options
});
Always configure nodes through the Manager

Properties

PropertyTypeDescriptionDefault
uuidStringUnique identifier for the node instanceGenerated
hostStringThe hostname of the Lavalink serverRequired
portNumberThe port of the Lavalink serverRequired
identifierStringA unique identifier for the node. If not provided, a UUID will be generated.Generated
passwordStringThe password for the Lavalink server."youshallnotpass"
pathVersionStringAPI version path for Lavalink"v4"
connectedBooleanWhether the node is connectedfalse
destroyedBooleanWhether the node has been destroyedfalse
reconnectTimeoutNodeJS.TimeoutCurrent reconnection timeoutundefined
reconnectAttemptsNumberNumber of reconnection attempts made0
retryAmountNumberMaximum number of reconnection attempts5
retryDelayNumberDelay between reconnection attempts (ms)60000
resumedBooleanWhether the node session was resumedfalse
resumeTimeoutNumberSession resume timeout (ms)60000
regionsArray<String>Voice regions associated with this node[]
secureBooleanWhether to use SSL/TLS connectionfalse
sessionIdStringThe current session IDGenerated
priorityNumberThe priority of the node for selectionundefined
socketWebSocketThe WebSocket connection to LavalinkCreated
statsINodeStatsNode statistics (CPU, memory, players)undefined
infoObjectAdditional node informationundefined
versionStringLavalink server versionundefined
urlStringBase URL for REST requestsGenerated
restRESTThe REST instance for making HTTP requestsCreated
stateNodeStateThe current state of the nodeDISCONNECTED
capabilitiesArray<String>Capabilities supported by the node (e.g., lavadspx, lavasearch)[]
pluginsMap<String, AbstractPlugin>Map of loaded plugins for this nodeMap

Methods

connect

connectmethod

Connect to Node

Establishes connection to the Lavalink server with optional session resuming. Sets the node state to CONNECTING.

Returns & Example

Returnsvoid

node.connect();

reconnect

reconnectmethod

Reconnect Node

Attempts to reconnect to the Lavalink server after a delay with exponential backoff. Sets the node state to CONNECTING. If reconnect attempts are exhausted, it attempts to migrate players to another node.

Returns & Example

Returnsvoid

node.reconnect();

destroy

destroymethod

Destroy Node

Closes the WebSocket connection and marks the node as destroyed. Unloads any loaded plugins for this node.

Returns & Example

Returnsvoid

node.destroy();

getPlayers

getPlayersmethod

Get Players

Gets all players connected to this node.

Returns & Example

ReturnsPlayer[] — Array of players connected to this node

const players = node.getPlayers();
console.log(`Players on node: ${players.length}`);

getPlayersCount

getPlayersCountproperty

Get Players Count

Gets the number of players connected to this node.

Returns & Example

Returnsnumber — Number of connected players

const count = node.getPlayersCount;
console.log(`Connected players: ${count}`);

getSystemStats

getSystemStatsmethod

Get System Stats

Retrieves CPU and memory usage statistics for the node.

Returns & Example

Returns{ cpuLoad: number; memoryUsage: number } — Object containing CPU load and memory usage

const stats = node.getSystemStats();
console.log(`CPU Load: ${stats.cpuLoad}%, Memory Usage: ${stats.memoryUsage} bytes`);

isOverloaded

isOverloadedmethod

Is Overloaded

Checks if the node is currently overloaded based on CPU and memory thresholds.

Parameters
cpuThresholdnumber
80
CPU usage percentage threshold
memoryThresholdnumber
80
Memory usage percentage threshold

Returns & Example

Returnsboolean — True if the node is overloaded, false otherwise

if (node.isOverloaded()) {
  console.log('Node is overloaded!');
}

migrateAllPlayers

migrateAllPlayersmethod

Migrate All Players

Migrates all players from this node to another specified node or the best available node.

Parameters
targetNodeNode
The target node to migrate players to. If not provided, the best available node will be chosen.

Returns & Example

ReturnsPromise<void>

await node.migrateAllPlayers();

getNodeStatus

getNodeStatusmethod

Get Node Status

Retrieves a comprehensive status report for the node, including connection, performance, and player information.

Parameters
timeoutnumber
2000
Timeout in milliseconds for the health check.

Returns & Example

Returnsobject — An object containing the node's status, including connected, version, stats (cpu, memory, uptime), players (total, active, paused, idle), and health (status, needsRestart, responding, performance).

const status = await node.getNodeStatus();
console.log(status);
/*
Example Output:
{
  identifier: 'Node-1',
  connected: true,
  version: '1.4.0',
  stats: {
    cpu: 0.5,
    memory: 1024000000,
    uptime: 123456789
  },
  players: {
    total: 5,
    active: 3,
    paused: 2,
    idle: 0
  },
  health: {
    status: 'stable',
    needsRestart: false,
    responding: true,
    performance: 'excellent'
  }
}
*/

Performance Considerations

  1. Load Balancing: Distribute players across multiple nodes for better performance.
  2. Monitoring: Regularly monitor node statistics to identify performance issues.
  3. Reconnection: Properly configure reconnection parameters to handle temporary disconnections.
  4. Regions: Associate nodes with specific regions to optimize voice latency.