簡體   English   中英

檢查 child_process 是否可以在 NodeJS 中運行命令

[英]Check if child_process can run a command in NodeJS

如何檢查 child_process 是否可以運行命令?

“echo”是可以在終端中運行的有效命令,但“echoes”不是一個。 例如,如果我這樣做

const cp = require('child_process')
cp.exec('echo hello')

它會起作用的。

如果我這樣做,雖然

const cp = require('child_process')
cp.exec('echoes hello') //notice how it is echoes instead of echo

它只會出錯,但也許用戶有一個向終端添加“回聲”的程序,在這種情況下,它可以運行,但如果出錯它只會退出進程,我不會能夠檢查它是否有效。

有沒有辦法做到這一點? 非常感謝您!

您必須手動遍歷$PATH env 中的目錄並在這些目錄上執行查找。 例如: $PATH設置為/bin:/usr/local/bin然后你必須執行

fs.access('/bin/' + command, fs.constants.X_OK)

fs.access('/usr/local/bin/' + command, fs.constants.X_OK)

解決方案看起來像這樣。

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)

注意:我認為我的解決方案僅適用於基於 *nix 的操作系統

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM