title: Synchronously checking if a child process failed to spawn in Node?
body: <p>I spawn a child process. After I spawn it, I write to the outgoing stream, so I want to synchronously detect if it failed to spawn before doing that (otherwise I get a <code>write EPIPE</code> error).</p>
  
  <pre><code>let proc = cp.spawn("path/file.exe");
  proc.on("error", (err) =&gt; { throw err; });
  proc.stdin.write(...);
  </code></pre>
  
  <p>Now if I put the <code>write</code> on a <code>setTimeout(() =&gt; { proc.stdin.write(...); }, 0)</code>, the <code>error</code> handler will get hit first, and we'll crash before doing the <code>write</code>, but that's a little ugly.</p>
  
  <p>What I have found is that after <code>cp.spawn</code> returns, we can check the <code>proc.pid</code> property, and if it's a number, we know that the process spawned. If we give it the path of a nonexistent executable, <code>proc.pid</code> is <code>undefined</code>, so it seems that we can synchronously check if the process failed to spawn, and we don't need to rely on the asynchronous <code>error</code> callback (though the callback catches other errors).</p>
  
  <p>Node's <a href="https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options" rel="nofollow noreferrer">documentation</a> has a section on checking for a failed spawn, but it suggests the asynchronous method:</p>
  
  <pre><code>const subprocess = spawn('bad_command');
  
  subprocess.on('error', (err) =&gt; {
    console.log('Failed to start subprocess.');
  });
  </code></pre>
  
  <p>Nowhere does it mention that checking for an <code>undefined</code> <code>proc.pid</code> is a suitable synchronous alternative for checking for a failed spawn, which me leads to wonder if this a robust and recommended way of doing it. Can anyone comment on this?</p>