我有一个独特的问题,我需要使用 Node 来迭代几个 Unix 风格的命令,并查看它们是否存在于 Windows 安装的 path
中。
例如,Windows 本身不支持 ls
。但是,假设有人安装了 git
并检查是否包含 Unix 命令,它会。
我需要知道ls
等命令是否在系统path
中。
现在,我正在使用 child_process
在每个命令上运行 help
。然后我检查运行它的响应。这是困惑和危险的。我不想从 Node 运行 30 条任意命令:
var spawnSync = require('child_process').spawnSync;
var out = spawnSync('ls', ['/?'], {encoding: 'utf8'});
我还能如何检查这些命令是否存在?
最佳答案
我个人发现 command-exists module在 npm 上效果很好。
安装
npm install command-exists
用法
异步
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 });
同步
var commandExistsSync = require('command-exists').sync; // returns true/false; doesn't throw if (commandExistsSync('ls')) { // proceed } else { // ... }
关于node.js - Node - 检查路径中是否存在命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953168/