Last active
December 26, 2022 13:24
-
-
Save tzafrirben/af1fc3e5bad1ce62a23af0daee460e83 to your computer and use it in GitHub Desktop.
Spawn child process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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