video-optimizer-bot / src /utils /process.utils.js
Hugging Face Deployer
Deploy bot to Hugging Face Spaces
03b405b
Raw History Blame Contribute Delete
1.59 kB
const { exec, spawn } = require('child_process');
const { promisify } = require('util');
const execPromise = promisify(exec);
/**
* Safely verify if a CLI binary command is available
* @param {string} command
* @param {Array<string>} args
* @returns {Promise<boolean>}
*/
async function checkBinary(command, args = ['--version']) {
try {
const { stdout } = await execPromise(`${command} ${args.join(' ')}`);
return stdout && stdout.length > 0;
} catch (err) {
return false;
}
}
/**
* Execute a spawn process with automated timeout protection
* @param {string} command
* @param {Array<string>} args
* @param {object} options
* @param {number} timeoutMs
* @returns {Promise<{stdout: string, stderr: string, code: number}>}
*/
function spawnWithTimeout(command, args, options = {}, timeoutMs = 30 * 60 * 1000) {
return new Promise((resolve, reject) => {
const proc = spawn(command, args, options);
let stdout = '';
let stderr = '';
const timer = setTimeout(() => {
proc.kill('SIGKILL');
reject(new Error(`Process execution of ${command} timed out after ${timeoutMs}ms`));
}, timeoutMs);
proc.stdout?.on('data', (data) => {
stdout += data.toString();
});
proc.stderr?.on('data', (data) => {
stderr += data.toString();
});
proc.on('close', (code) => {
clearTimeout(timer);
resolve({ stdout, stderr, code });
});
proc.on('error', (err) => {
clearTimeout(timer);
reject(err);
});
});
}
module.exports = { execPromise, checkBinary, spawnWithTimeout };