Skip to content

Feature request: ChildProcess 'spawn' event #35288

Closed
@zenflow

Description

@zenflow

Is your feature request related to a problem? Please describe.

After calling child_process.spawn, I'd like to know when the child process has successfully spawned and there's no longer the possibility of an 'error' event from failing to spawn (i.e. error type # 1 in the docs for that 'error' event, e.g. EPERM, ENOENT).

Currently I just wait 100 milliseconds (after calling child_process.spawn), and if the child process hasn't emitted an 'error' event by that time, I assume it spawned successfully. My code looks something like this:

const { spawn } = require('child_process');
const { promisify } = require('util');
const { once } = require('events');
const timeout = promisify(setTimeout);

async function doSomethingWithChildProcess(){
  const subprocess = spawn(...spawnArgs));
  await Promise.race([
    timeout(100),
    once(subprocess, 'error').then(([error]) => Promise.reject(error))
  ]);
  // now do something with the running child process...
}

This seems to work, but I'm not sure how reliable it is, and anyways, it is certainly a hack.
I'm wondering if there could be a better (more correct) way..

Describe the solution you'd like

Is there some point of execution in Node where we know there was no error spawning the child process?

If so, we could introduce a new 'spawn' event for the ChildProcess class, to be emitted at that point in execution?

That would remove the need for the unreliable hack I described above.

It would also work nicely with Node.js's events.once function. For example, the code from above could be updated like this:

 const { spawn } = require('child_process');
-const { promisify } = require('util');
 const { once } = require('events');
-const timeout = promisify(setTimeout);

 async function doSomethingWithChildProcess(){
   const subprocess = spawn(...spawnArgs);
-  await Promise.race([
-    timeout(100),
-    once(subprocess, 'error').then(([error]) => Promise.reject(error))
-  ]);
+  await once(subprocess, 'spawn');
   // now do something with the running child process...
 }

Describe alternatives you've considered

Just the hack I described above (of expecting any error spawning to happen within 100 milliseconds of calling child_process.spawn).

I can't think of any other possible solutions at this time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    child_processIssues and PRs related to the child_process subsystem.feature requestIssues that request new features to be added to Node.js.good first issueIssues that are suitable for first-time contributors.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions