Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node - check existence of command in path

I have a unique problem where I need to use Node to iterate over several Unix-style commands and see if they exist in the path of a Windows installation.

For instance, Windows doesn't support ls natively. However, supposing someone installed git and checked to include Unix commands, it would.

I need to know whether or not ls and other commands are in the system path.

Right now, I'm using child_process to run help on each command. I then check the response of running it. This is messy and dangerous. I don't want to run 30 arbitrary commands from Node:

var spawnSync = require('child_process').spawnSync;
var out = spawnSync('ls', ['/?'], {encoding: 'utf8'});

How else can I check for the existence of these commands?

like image 647
dthree Avatar asked Jan 22 '16 18:01

dthree


People also ask

How do I validate a path in node JS?

Any Node. Js version. const fs = require("fs"); let path = "/path/to/something"; fs. lstat(path, (err, stats) => { if(err) return console.

How do I know if a node is in path?

To check if a path is a directory in Node. js, we can use the stat() (asynchronous execution) function or the statSync() (synchronous execution) function from the fs (filesystem) module and then use the isDirectory() method returned from the stats object.

How do I find the path of a node js file?

To check the path in synchronous mode in fs module, we can use statSync() method. The fs. statSync(path) method returns the instance of fs. Stats which is assigned to variable stats.


1 Answers

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 {
        // ...
    }
    
like image 130
Scott Avatar answered Oct 08 '22 19:10

Scott