Home > Enterprise >  Check if child_process can run a command in NodeJS
Check if child_process can run a command in NodeJS

Time:08-14

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!

CodePudding user response:

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 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

  • Related