Skip to content

Instantly share code, notes, and snippets.

@jmpinit
Last active February 22, 2020 20:06
Show Gist options
  • Save jmpinit/7a3aa580efffdef50fa9f0dd3d068d6f to your computer and use it in GitHub Desktop.
Save jmpinit/7a3aa580efffdef50fa9f0dd3d068d6f 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);
});
}
@otiai10
Copy link

otiai10 commented Feb 7, 2020

@jmpinit
Copy link
Author

jmpinit commented Feb 22, 2020

@otiai10 thanks your package is a better general solution to this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment