From 58989a9b7e6e123aab02af5d73373d8b8d5fcfb4 Mon Sep 17 00:00:00 2001 From: Bsian Date: Mon, 4 May 2020 00:25:04 +0100 Subject: [PATCH] Improve exec system --- src/class/Util.ts | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/class/Util.ts b/src/class/Util.ts index 3328565..58f933a 100644 --- a/src/class/Util.ts +++ b/src/class/Util.ts @@ -1,6 +1,5 @@ /* eslint-disable no-param-reassign */ -import { promisify } from 'util'; -import childProcess from 'child_process'; +import { exec, ExecOptions } from 'child_process'; import nodemailer from 'nodemailer'; import { Message, PrivateChannel, GroupChannel, Member, User } from 'eris'; import uuid from 'uuid/v4'; @@ -31,16 +30,27 @@ export default class Util { * @param command The command to execute * @param options childProcess.ExecOptions */ - public async exec(command: string, options: childProcess.ExecOptions = {}): Promise { - const ex = promisify(childProcess.exec); - let result: string; - try { - const res = await ex(command, options); - result = `${res.stdout}${res.stderr}`; - } catch (err) { - return Promise.reject(new Error(`Command failed: ${err.cmd}\n${err.stderr}${err.stdout}`)); - } - return result; + public async exec(command: string, options: ExecOptions = {}): Promise { + return new Promise((res, rej) => { + let error = false; + let output = ''; + const writeFunction = (data: string|Buffer|Error) => { + if (data instanceof Error) error = true; + output += `${data}`; + }; + const cmd = exec(command, options); + cmd.stdout.on('data', writeFunction); + cmd.stderr.on('data', writeFunction); + cmd.on('error', writeFunction); + cmd.once('close', (code, signal) => { + output += `Command exited with code ${code}${signal ? `/${signal}` : ''}`; + cmd.stdout.removeListener('data', writeFunction); + cmd.stderr.removeListener('data', writeFunction); + cmd.removeListener('error', writeFunction); + if (error) rej(output); + res(output); + }); + }); } /**