您必须手动循环遍历$PATH
个环境中的目录,并对这些目录执行查找.
如果将$PATH
设置为/bin:/usr/local/bin
,则必须执行
fs.access('/bin/' + comm和, fs.constants.X_OK)
和
fs.access('/usr/local/bin/' + comm和, fs.constants.X_OK)
解决方案应该是这样的.
const fs = require('fs/promises')
const path = require('path')
const paths = process.env.PATH.split(':')
async function isExecutable(comm和) {
const cases = []
for (const p of paths) {
const bin = path.join(p, comm和)
cases.push(fs.access(bin, fs.constants.X_OK))
}
await Promise.any(cases)
return comm和
}
const found = (bin) => console.log('found', bin)
const notfound = (errors) => {
console.log('not found or not executable')
// console.error(errors)
}
// passes
isExecutable('echo').then(found).catch(notfound)
isExecutable('node').then(found).catch(notfound)
// fails
isExecutable('shhhhhh').then(found).catch(notfound)
isExecutable('echoes').then(found).catch(notfound)
注意:我认为我的解决方案只能在基于NIX的操作系统上运行