[英]Check if child_process can run a command in NodeJS
how can I check if child_process can run a command?如何检查 child_process 是否可以运行命令?
'echo' is a valid command that can be run in a terminal, but 'echoes' is not one. “echo”是可以在终端中运行的有效命令,但“echoes”不是一个。 For example, if I do this例如,如果我这样做
const cp = require('child_process')
cp.exec('echo hello')
it will work.它会起作用的。
If I do this, though如果我这样做,虽然
const cp = require('child_process')
cp.exec('echoes hello') //notice how it is echoes instead of echo
it will just error, but maybe the user has a program that adds 'echoes' to a terminal, and in that case, it would be able to run, but if it errors it will just exit out of the process and I won't be able to check if it works.它只会出错,但也许用户有一个向终端添加“回声”的程序,在这种情况下,它可以运行,但如果出错它只会退出进程,我不会能够检查它是否有效。
Is there any way to do this?有没有办法做到这一点? Thank you so much in advance!非常感谢您!
You have to manually loop through dirs in $PATH
env & perform look up on those directory.您必须手动遍历$PATH
env 中的目录并在这些目录上执行查找。 eg: $PATH
is set to /bin:/usr/local/bin
then you have to perform例如: $PATH
设置为/bin:/usr/local/bin
然后你必须执行
fs.access('/bin/' + command, fs.constants.X_OK)
and和
fs.access('/usr/local/bin/' + command, fs.constants.X_OK)
solution would look like this.解决方案看起来像这样。
const fs = require('fs/promises')
const path = require('path')
const paths = process.env.PATH.split(':')
async function isExecutable(command) {
const cases = []
for (const p of paths) {
const bin = path.join(p, command)
cases.push(fs.access(bin, fs.constants.X_OK))
}
await Promise.any(cases)
return command
}
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)
NOTE: I think my solution works only on *nix based OSs注意:我认为我的解决方案仅适用于基于 *nix 的操作系统
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.