Skip to content

Commit 17156a3

Browse files
dfabulichaduh95
authored andcommitted
doc: recommend events.once to manage 'close' event
`events.once` is a great way to manage the `close` / `error` / `exit` events of a child process. It creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. I think a lot of people wrongly think that managing a spawned child process requires writing boilerplate handlers for `close` and `error`, and that there's no `promisify` solution for spawned child processes. In fact, `events.once` is that solution. The docs should explicitly recommend it in examples. PR-URL: #60017 Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
1 parent 6e26ccc commit 17156a3

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

doc/api/child_process.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ ls.on('close', (code) => {
2929

3030
```mjs
3131
import { spawn } from 'node:child_process';
32+
import { once } from 'node:events';
3233
const ls = spawn('ls', ['-lh', '/usr']);
3334

3435
ls.stdout.on('data', (data) => {
@@ -39,9 +40,8 @@ ls.stderr.on('data', (data) => {
3940
console.error(`stderr: ${data}`);
4041
});
4142

42-
ls.on('close', (code) => {
43-
console.log(`child process exited with code ${code}`);
44-
});
43+
const [code] = await once(ls, 'close');
44+
console.log(`child process exited with code ${code}`);
4545
```
4646

4747
By default, pipes for `stdin`, `stdout`, and `stderr` are established between
@@ -770,6 +770,7 @@ ls.on('close', (code) => {
770770
771771
```mjs
772772
import { spawn } from 'node:child_process';
773+
import { once } from 'node:events';
773774
const ls = spawn('ls', ['-lh', '/usr']);
774775

775776
ls.stdout.on('data', (data) => {
@@ -780,9 +781,8 @@ ls.stderr.on('data', (data) => {
780781
console.error(`stderr: ${data}`);
781782
});
782783

783-
ls.on('close', (code) => {
784-
console.log(`child process exited with code ${code}`);
785-
});
784+
const [code] = await once(ls, 'close');
785+
console.log(`child process exited with code ${code}`);
786786
```
787787
788788
Example: A very elaborate way to run `ps ax | grep ssh`
@@ -1481,6 +1481,7 @@ ls.on('exit', (code) => {
14811481
14821482
```mjs
14831483
import { spawn } from 'node:child_process';
1484+
import { once } from 'node:events';
14841485
const ls = spawn('ls', ['-lh', '/usr']);
14851486

14861487
ls.stdout.on('data', (data) => {
@@ -1494,6 +1495,9 @@ ls.on('close', (code) => {
14941495
ls.on('exit', (code) => {
14951496
console.log(`child process exited with code ${code}`);
14961497
});
1498+
1499+
const [code] = await once(ls, 'close');
1500+
console.log(`child process close all stdio with code ${code}`);
14971501
```
14981502
14991503
### Event: `'disconnect'`

0 commit comments

Comments
 (0)