-
-
Save patevs/03034003d65fa5e0413811299c022a46 to your computer and use it in GitHub Desktop.
Node.js: Check if a command exists
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
// 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