Skip to content

Instantly share code, notes, and snippets.

@tzafrirben
Last active December 26, 2022 13:24
Show Gist options
  • Save tzafrirben/af1fc3e5bad1ce62a23af0daee460e83 to your computer and use it in GitHub Desktop.
Save tzafrirben/af1fc3e5bad1ce62a23af0daee460e83 to your computer and use it in GitHub Desktop.
Spawn child process
import { spawn } from 'child_process';
export const execCommand = async (
command: string,
workDir: string
): Promise<{ stdout: string; stderr: string; code: number }> => {
return new Promise((resolve, reject) => {
const childProcess = spawn(command, {
shell: true,
cwd: workDir
});
let stdout = '';
childProcess.stdout.on('data', data => {
stdout = stdout + data.toString();
});
let stderr = '';
childProcess.stderr.on('data', data => {
stderr = stderr + data.toString();
});
childProcess.on('close', code => {
if (code === 0) {
resolve({ stdout, stderr, code });
} else {
reject(new Error(stderr.trim()));
}
});
childProcess.on('error', err => {
reject(err);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment