Node - check existence of command in path
Personally I have found that the command-exists module on npm works great.
Installation
npm install command-exists
Usage
async
var commandExists = require('command-exists'); commandExists('ls', function(err, commandExists) { if(commandExists) { // proceed confidently knowing this command is available } });
promise
var commandExists = require('command-exists'); // invoked without a callback, it returns a promise commandExists('ls') .then(function(command){ // proceed }).catch(function(){ // command doesn't exist });
sync
var commandExistsSync = require('command-exists').sync; // returns true/false; doesn't throw if (commandExistsSync('ls')) { // proceed } else { // ... }
You could use whereis
in Linux, and where
in Windows, to see if the executable can be found
var isWin = require('os').platform().indexOf('win') > -1;
var where = isWin ? 'where' : 'whereis';
var spawn = require('child_process').spawn;
var out = spawn(where + ' ls', ['/?'], {encoding: 'utf8'});
out.on('close', function (code) {
console.log('exit code : ' + code);
});
DON'T use child_process
just for that, neither packages which use child_process
internally. As Matt already answered, the most straightforward way is just checking under your Path.
Here is a NPM lookpath
package which scans your $PATH
or $Path
.
const { lookpath } = require('lookpath');
const p = await lookpath('bash');
// "/bin/bash"
This is a Node.js port of exec.LookPath
from Go.
Hope it helps