Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Check if child_process can run a command in NodeJS

how can I check if child_process can run a command?

'echo' is a valid command that can be run in a terminal, but 'echoes' is not one. 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!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have to manually loop through dirs in $PATH env & perform look up on those directory. eg: $PATH is set to /bin:/usr/local/bin then you have to perform

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 { constants: fsconsts } = require('fs')
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, fsconsts.X_OK)) // X_OK is bit flag which makes sure file is executable
  }
  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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda