Last active
April 26, 2022 13:34
-
-
Save ValentaTomas/cd714aa62a0b1cfd08bb941700f205c8 to your computer and use it in GitHub Desktop.
Execute Shell command in Node
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 { 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