mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-09 16:13:31 +01:00
* add respawn thing for shards, and make it easier to recieve messages from shards * run docs
56 lines
1.3 KiB
JavaScript
56 lines
1.3 KiB
JavaScript
const childProcess = require('child_process');
|
|
const path = require('path');
|
|
|
|
/**
|
|
* Represents a Shard spawned by the ShardingManager.
|
|
*/
|
|
class Shard {
|
|
/**
|
|
* @param {ShardingManager} manager The sharding manager
|
|
* @param {number} id The ID of this shard
|
|
*/
|
|
constructor(manager, id) {
|
|
/**
|
|
* The manager of the spawned shard
|
|
* @type {ShardingManager}
|
|
*/
|
|
this.manager = manager;
|
|
|
|
/**
|
|
* The shard ID
|
|
* @type {number}
|
|
*/
|
|
this.id = id;
|
|
|
|
/**
|
|
* The process of the shard
|
|
* @type {ChildProcess}
|
|
*/
|
|
this.process = childProcess.fork(path.resolve(this.manager.file), [id, this.manager.shards.size]);
|
|
|
|
this.process.once('exit', () => {
|
|
if (this.manager.respawn) this.manager.createShard(this.id);
|
|
});
|
|
|
|
this.process.on('message', message => {
|
|
this.manager.emit('message', this, message);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Sends a message to the shard's process.
|
|
* @param {*} message Message to send to the shard
|
|
* @returns {Promise<Shard>}
|
|
*/
|
|
send(message) {
|
|
return new Promise((resolve, reject) => {
|
|
const sent = this.process.send(message, err => {
|
|
if (err) reject(err); else resolve(this);
|
|
});
|
|
if (!sent) throw new Error('Failed to send message to shard\'s process.');
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = Shard;
|