I am using spawn
to spawn a long running process that sends output over time to stdio, and is read and processed by my nodejs script. The tricky part is that I cannot guarantee that the command sent will always be valid. How can I catch an error in spawning? Preferably this will not involve installing a global exception handler, since I don't want to handle any other exceptions. (If that's the only way, I would need to figure out when the spawned process has started up correctly and then uninstall the handler, which is a mess I'd rather not get into.)
The code I want to run would be something like this:
var spawn = require('child_process').spawn; try { spawn("zargle"); } catch (e) { console.error("I'm handling the error!"); }
But this just raises an uncaughtException somewhere in the node event loop, presumably because the call is async and didn't even try to start the child process on my script's time slice.
The only exceptions that need to be caught are when spawn fails to start the process at all (for example, the name is incorrect and ENOENT is thrown). I am not (at this time) concerned with any problems the spawned process might generate on its own.
Similar but different: How do I debug "Error: spawn ENOENT" on node.js?
I know exactly why I am getting ENOENT, and I know what to change to have the error not happen. My question is how to gracefully respond to this situation if the error is unavoidable.
The reason the spawn was broken in the first place was because we were overriding the child process' environment variables in options.env which it normally would have inherited from its parent process. So without the PATH environment variable, the operating system doesn't know where to look for the node executable.
There are four different ways to create a child process in Node: spawn (), fork (), exec (), and execFile (). We’re going to see the differences between these four functions and when to use each.
Node.js streams have a reputation for being hard to work with, and even harder to understand. Well I’ve got good news… We can easily spin a child process using Node’s child_process module and those child processes can easily communicate with each other with a messaging system.
We simply destructure the spawn function out of the child_process module and execute it with the OS command as the first argument. The result of executing the spawn function (the child object above) is a ChildProcess instance, which implements the EventEmitter API.
As with many things in node, child processes can emit an error
event. Add a listener for that and you will be able to catch it (no try-catch
needed):
var spawn = require('child_process').spawn; var child = spawn('foo'); child.on('error', function(err) { console.log('Oh noez, teh errurz: ' + err); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With