Knucklehead
Knucklehead

Reputation: 97

child_process.spawn() isn't waiting for child node process to complete

The following works as expected, waiting for 3 seconds before exiting:

child_process.spawn( 'sleep', [3] );

but this is exiting immediately, not waiting for 3 seconds as it should (and as it does when this command is run directly:

child_process.spawn( 'node', ['-e', '"setTimeout(null, 3000);"'] );

Any ideas as to why? Thanks.

Edit: spawnSync() behaves the same way in both cases. Also, I'm not expecting the spawn() function to block, I'm expecting the node process to wait for its children to exit before exiting itself.

Upvotes: 1

Views: 697

Answers (1)

Trott
Trott

Reputation: 70075

The problem is the double quotation marks. That makes your program execution just a string rather than a setTimeout() function call. Use this instead:

child_process.spawn( 'node', ['-e', 'setTimeout(null, 3000);'] );

Note the removal of the double quotation marks around setTimeout().

With the double quotation marks, it's effectively the same as running this from the command line (assuming a Unix-like operating system/shell):

'node' '-e' '"setTimeout(null, 3000);"'

Try it and you'll see it returns right away because the last argument is just a string value that doesn't need to be parsed and executed. Then try this:

'node' '-e' 'setTimeout(null, 3000);'

That will wait three seconds like you expect.

Upvotes: 1

Related Questions