Skip to content

Instantly share code, notes, and snippets.

@patevs
Forked from jmpinit/cmd-exists.js
Created October 29, 2019 12:13
Show Gist options
  • Save patevs/03034003d65fa5e0413811299c022a46 to your computer and use it in GitHub Desktop.
Save patevs/03034003d65fa5e0413811299c022a46 to your computer and use it in GitHub Desktop.
Node.js: Check if a command exists
// returns a Promise which fulfills with the result of a shell command
// rejects with stderr
function run(command) {
return new Promise((fulfill, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) {
reject(err);
return;
}
if (stderr) {
reject(new Error(stderr));
return;
}
fulfill(stdout);
});
});
}
// returns Promise which fulfills with true if command exists
function exists(cmd) {
return run(`which ${cmd}`).then((stdout) => {
if (stdout.trim().length === 0) {
// maybe an empty command was supplied?
// are we running on Windows??
return Promise.reject(new Error('No output'));
}
const rNotFound = /^[\w\-]+ not found/g;
if (rNotFound.test(cmd)) {
return Promise.resolve(false);
}
return Promise.resolve(true);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment