节点 - 检查路径中命令的存在

dth*_*ree 9 command path node.js

我有一个独特的问题,我需要使用Node迭代几个Unix风格的命令,看看它们是否存在于pathWindows安装中.

例如,Windows本身不支持ls.但是,假设有人安装git并检查了包含Unix命令,它会.

我需要知道系统中是否有ls其他命令path.

现在,我正在使用每个命令child_process运行help.然后我检查运行它的响应.这是混乱和危险的.我不想从Node运行30个任意命令:

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

我怎样才能检查这些命令的存在?

Sco*_*ott 6

我个人发现npm上的command-exists模块效果很好。

安装

npm install command-exists
Run Code Online (Sandbox Code Playgroud)

用法

  • 异步的

    var commandExists = require('command-exists');
    
    commandExists('ls', function(err, commandExists) {
    
        if(commandExists) {
            // proceed confidently knowing this command is available
        }
    
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • 诺言

    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
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • 同步

    var commandExistsSync = require('command-exists').sync;
    // returns true/false; doesn't throw
    if (commandExistsSync('ls')) {
        // proceed
    } else {
        // ...
    }
    
    Run Code Online (Sandbox Code Playgroud)


ade*_*neo 5

您可以whereis在Linux和whereWindows中使用,以查看是否可以找到可执行文件

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);
});
Run Code Online (Sandbox Code Playgroud)


oti*_*i10 5

不要仅用child_process于此目的,也不要使用child_process内部使用的包。正如马特已经回答的那样,最直接的方法就是检查你的路径。

这是一个 NPMlookpath包,可以扫描您的$PATH$Path.

const { lookpath } = require('lookpath');

const p = await lookpath('bash');
// "/bin/bash"
Run Code Online (Sandbox Code Playgroud)

这是 Go 的 Node.js 端口exec.LookPath

希望能帮助到你