Check if git is installed using Node

Asked

Viewed 431 times

8

I’m starting in a desktop application with the use of Electron however I need to check if there is Git installed on the system because it must use git

As the idea is to distribute on Windows, Linux and Mac and the verification should occur to each "startup" of the application as I can check this on Linux and Mac?

What I have for now:

const {
    spawn,
    spawnSync,
    exec,
    execSync,
    execFileSync,
} = require('child_process')

switch(process.platform){
    case'win32':
        let git = spawn('cmd.exe', ['/c', 'git --version'])
        git.stdout.on('data', (data) => {
            // logic...
        });
        break;
    case'linux':
        //
        break;
    case'darwin':
        //
        break;
    default:
        // unsupported
    break;
}

2 answers

8


I haven’t had a chance to use Node and everything, but I think you can call git straight, you don’t have to call the shell executable to do this.

let git = spawn('git', ['--version'])

Even, for what you want, according to the link I will put in the source, execFile is more used for this:

const child = execFile('git', ['--version'], (error, stdout, stderr) => {
  if (error) {
      console.error('stderr', stderr);
      throw error;
  }
  console.log('stdout', stdout);
});

When?

execFile is used when we only need to run an application and get the output. For example, we can use execFile to run a image processing application like Imagemagick for convert a PNG image to JPG format and we just we care whether it succeeds or not. Execfile should not be used when the external application produces a large amount of data and we need to consume this data in real time.

Source

https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node

0

The simplest solution I could think of was this:

const platform = process.platform
const { spawn } = require('child_process')
const where = platform === 'win32' ? 'where' : 'which'
const out = spawn(where, ['ls'])

out.on('close', (code) => {
  console.log(`child process exited with code ${code}`) // 0 se o comando existe, 1 se não existe
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.