Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Last active April 26, 2022 13:34
Show Gist options
  • Save ValentaTomas/cd714aa62a0b1cfd08bb941700f205c8 to your computer and use it in GitHub Desktop.
Save ValentaTomas/cd714aa62a0b1cfd08bb941700f205c8 to your computer and use it in GitHub Desktop.
Execute Shell command in Node
import { exec, execFile } from 'child_process';
function executeCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout) => {
if (error) {
return reject(error);
}
return resolve(stdout);
});
});
}
async function executeCommandWithPath(command: string, shellPath?: string): Promise<string> {
const defaultShell = shellPath || process.env.SHELL || await executeCommand('echo $SHELL');
return new Promise((resolve, reject) => {
execFile(defaultShell, ['-i', '-l', '-c', command], (error, stdout, stderr) => {
if (error || stderr) {
// Warning - this promise does not throw error
console.error(error + stderr);
}
return resolve(stdout);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment