const { exec } = require("child_process"); const fs = require('fs'); class Server { constructor(dir) { this.rootDir = dir; this.name = dir.split('/').at(-1); this.pidFilePath = this.rootDir + '/pid.txt'; // read version file var versionFilePath = this.rootDir + '/current_version.txt'; if (fs.existsSync(versionFilePath)) { this.version = fs.readFileSync(versionFilePath, {encoding:'utf8', flag:'r'}); } } start() { console.log(`Starting server ${this.name}...`); // create shell command and execute it let cmd = `${this.rootDir}/start.sh`; exec(cmd, (err, stdout, stderr) => { if (err) { console.log(`Error while starting server: ${error.message}`); } console.log(`Server ${this.name} has been started.`); }); } stop() { console.log(`Stopping server ${this.name}...`); } getStatus() { if (fs.existsSync(this.pidFilePath)) { let pid = fs.readFileSync(this.pidFilePath, {encoding: 'utf8', flag: 'r'}); try { return process.kill(pid, 0); } catch (err) { // ESRCH error means the process doesn't exist, so should return false if (err.code !== 'ESRCH') { console.error(err); return err.code === 'EPERM'; } else { // delete pid.txt so we don't have to worry about checking it again fs.unlinkSync(this.pidFilePath); } } } return false } getPid() { if (fs.existsSync(this.pidFilePath)) { return fs.readFileSync(this.pidFilePath, {encoding:'utf8', flag:'r'}) } return -1; } } exports.Server = Server;