Search code examples
javascriptnode.jselectronspawn

Electron NodeJS spawn error when running certain commands: spawn ENOENT


So, I'm trying to use spawn in my Electron application to run the flutter --version command. This command works perfectly fine on my terminal.

Every solution I've seen implies I don't have it in my process.env.PATH variable. But when I do a console.log( process.env.PATH );, the path to my Flutter command is there.

Here is the current code I'm trying to execute:

const flutterVer = spawn('flutter', ['--version', '/c']);

flutterVer.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

Which returns:

Uncaught Error: spawn flutter ENOENT
    at __node_internal_captureLargerStackTrace (node:internal/errors:464:5)
    at __node_internal_errnoException (node:internal/errors:594:12)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:477:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

I tried testing with another command, like git --version, and that worked perfectly fine.


Solution

  • I've found a neat workaround by using exec instead of spawn like so.

    const { exec } = require('child_process');
    
    const flutterVer = exec('flutter --version');
    
    flutterVer.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });
    

    Will have too look into what the differences are between exec and spawn, but for now, it does what I need.