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: https://github.com/nodejs/node/pull/60017
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
This commit is contained in:
Dan Fabulich authored and Antoine du Hamel committed 2025-11-13 22:44:23 +01:00
1 parent 58bff04cc2
commit ea7ecb517b
1 file changed
+10 -6
+10 -6
View File
@@ -29,6 +29,7 @@ ls.on('close', (code) => {
```mjs
import { spawn } from 'node:child_process';
import { once } from 'node:events';
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
@@ -39,9 +40,8 @@ ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
const [code] = await once(ls, 'close');
console.log(`child process exited with code ${code}`);
```
By default, pipes for `stdin`, `stdout`, and `stderr` are established between
@@ -772,6 +772,7 @@ ls.on('close', (code) => {
```mjs
import { spawn } from 'node:child_process';
import { once } from 'node:events';
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
@@ -782,9 +783,8 @@ ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
const [code] = await once(ls, 'close');
console.log(`child process exited with code ${code}`);
```
Example: A very elaborate way to run `ps ax | grep ssh`
@@ -1483,6 +1483,7 @@ ls.on('exit', (code) => {
```mjs
import { spawn } from 'node:child_process';
import { once } from 'node:events';
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
@@ -1496,6 +1497,9 @@ ls.on('close', (code) => {
ls.on('exit', (code) => {
console.log(`child process exited with code ${code}`);
});
const [code] = await once(ls, 'close');
console.log(`child process close all stdio with code ${code}`);
```
### Event: `'disconnect'`