Skip to content

Feature request: ChildProcess 'spawn' event #35288

Closed

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.

Activity

  1. added
    child_processIssues and PRs related to the child_process subsystem.
    feature requestIssues requesting new Node.js features.
    on Sep 22, 2020
  2. bnoordhuis commented on Sep 22, 2020

    @bnoordhuis
    Member

    It's not hard to implement, see diff. Feel free to steal for a PR, no attribution needed. Needs docs and tests, however.

    Details
    diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js
    index 31d9f02df3..5672f3429f 100644
    --- a/lib/internal/child_process.js
    +++ b/lib/internal/child_process.js
    @@ -400,6 +400,8 @@ ChildProcess.prototype.spawn = function(options) {
         this._handle.close();
         this._handle = null;
         throw errnoException(err, 'spawn');
    +  } else {
    +    process.nextTick(onSpawnNT, this);
       }
     
       this.pid = this._handle.pid;
    @@ -465,6 +467,11 @@ function onErrorNT(self, err) {
     }
     
     
    +function onSpawnNT(self) {
    +  self.emit('spawn');
    +}
    +
    +
     ChildProcess.prototype.kill = function(sig) {
     
       const signal = sig === 0 ? sig :

    Apropos this:

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

    Yes, but there's a subtlety that is likely to trip up some people (mostly the magical thinker kind): while bash bob spawns successfully, bash then fails to spawn bob. You'll still get a spawn event.

    That caveat also applies to { shell: true } and it seems to be a perennial source of confusion to novice users who expect it to DWIM rather than do what the documentation says it does.

  3. kaushik94 commented on Sep 22, 2020

    @kaushik94

    @bnoordhuis can I take this up?

  4. zenflow commented on Sep 22, 2020

    @zenflow
    ContributorAuthor

    I'd also like to claim this issue 😄 @kaushik94 Would that be ok with you?

  5. kaushik94 commented on Sep 22, 2020

    @kaushik94

    @zenflow I'm sorry, I thought you were a maintainer. Sure you claim the issue as you raised the issue. Thanks, looking forward!

  6. zenflow commented on Sep 22, 2020

    @zenflow
    ContributorAuthor

    Thanks @kaushik94 😃

  7. alexp1917 commented on Mar 19, 2021

    @alexp1917

    this this event never fire sometimes? the docs say "if emitted" but don't specify why it wouldn't be. It is sometimes not emitted when things to smoothly (on windows, i am doing var child = spawn('yarn.cmd'); then listening for all events right away - and seeing an exit and close but not a spawn event. thanks

  8. zenflow commented on Mar 20, 2021

    @zenflow
    ContributorAuthor

    @alexp1917 Yeah I agree the docs could be more explicit about the case where this event does not fire. Please see my PR and let me know if it makes things perfectly clear: https://github.com/nodejs/node/pull/37833/files

    @alexp1917

    • Are you always using a supported Node.js version? This event was only added as of v15.1.0.
    • Is the 'error' event not firing in these cases where 'spawn' is not fired? Either a 'spawn' event or an 'error' event should fire, every time.

    If the answer to both of these questions is "yes", then I think we may have a bug in this feature..

  9. alexp1917 commented on Mar 20, 2021

    @alexp1917
  10. sylann commented on Jun 10, 2021

    @sylann

    I also have a case of missing 'spawn' event but only in certain circonstances.

    With node v15 on macos, it works
    With node v16 on a windows vm on this same mac, it works too.

    However, if I run the spawn command from an electron main process on the windows vm,
    then I never get a "spawn" event even though the child process has started successfully.
    I never get and "error" event either.

    So I ended up adding a terrible setTimeout to resolve automatically if no error occured.

    Side notes, I have tried spawning .exe files and .bat files or linux programs such as 'ls' and it doesn't change what I've said above.

  11. qnimbus commented on May 23, 2022

    @qnimbus
  12. qnimbus commented on May 23, 2022

    @qnimbus

    Note: I accidentally hid my previous comment - this is an unhidden copy of that comment

    public spawn = (): Promise<void> => {
        return new Promise((resolve, reject) => {
          const cp = spawn(cmd, [], {
            cwd: process.cwd(),
            env: process.env,
            stdio: ['pipe', 'pipe', process.stderr ],        
          });
      
          // Register listeners once the child has spawned
          cp.on('spawn', function () {
            // Resolve promise
            return resolve();
          });
    
          cp.on('error', (err: Error) => {
            // Reject promise
            return reject(err);
          });
        });
      };
    

    I seem to experience this issue too - the 'error' event never fires and my child process seems to spawn succesfully (judging by the output on my console) but the 'spawn' event also never fires. Or maybe it fires before the event handler is registered, but either way - the above code does not work for me.

    I've managed to 'fix' this issue with a bit of a hack - With the absence of the 'error' event getting thrown, I'm running a while-loop until cp.connected == true after which I return the resolved promise:

    while (!this._childProcess.connected); return resolve();
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    child_processIssues and PRs related to the child_process subsystem.feature requestIssues requesting new Node.js features.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