Files
DRB-Client/modules/serviceHandler.mjs
2024-05-12 12:55:00 -04:00

59 lines
1.8 KiB
JavaScript

import { exec } from 'child_process';
/**
* Executes a system command with error handling.
* @param {string} command The command to execute.
* @returns {Promise<{ stdout: string, stderr: string }>} A promise resolving to an object containing stdout and stderr.
*/
const executeCommand = (command) => {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Command failed with error: ${error.message}`);
resolve({ stdout, stderr });
} else {
resolve({ stdout, stderr });
}
});
});
};
/**
* Starts the given service from the command line.
* @param {string} serviceName The service name to be started.
* @returns {Promise<void>}
*/
export const startService = async (serviceName) => {
try {
await executeCommand(`sudo systemctl start ${serviceName}.service`);
} catch (error) {
console.error(`Failed to start service: ${error.message}`);
}
};
/**
* Restarts the given service from the command line.
* @param {string} serviceName The service name to be restarted.
* @returns {Promise<void>}
*/
export const restartService = async (serviceName) => {
try {
await executeCommand(`sudo systemctl restart ${serviceName}.service`);
} catch (error) {
console.error(`Failed to restart service: ${error.message}`);
}
};
/**
* Stops the given service from the command line.
* @param {string} serviceName The service name to be stopped.
* @returns {Promise<void>}
*/
export const stopService = async (serviceName) => {
try {
await executeCommand(`sudo systemctl stop ${serviceName}.service`);
} catch (error) {
console.error(`Failed to stop service: ${error.message}`);
}
};