Skip to content

Commit 0bb53a7

Browse files
cjihrigaddaleax
authored andcommitted
doc: make socket IPC examples more robust
This commit aims to improve the documentation examples that send sockets over IPC channels. Specifically, pauseOnConnect is added to a server that inspects the socket before sending and a 'message' handler adds a check that the socket still exists. PR-URL: #13196 Reviewed-By: Santiago Gimeno <[email protected]> Reviewed-By: Refael Ackermann <[email protected]>
1 parent f49dd21 commit 0bb53a7

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

doc/api/child_process.md

+13-3
Original file line numberDiff line numberDiff line change
@@ -1141,8 +1141,9 @@ handle connections with "normal" or "special" priority:
11411141
const normal = require('child_process').fork('child.js', ['normal']);
11421142
const special = require('child_process').fork('child.js', ['special']);
11431143

1144-
// Open up the server and send sockets to child
1145-
const server = require('net').createServer();
1144+
// Open up the server and send sockets to child. Use pauseOnConnect to prevent
1145+
// the sockets from being read before they are sent to the child process.
1146+
const server = require('net').createServer({ pauseOnConnect: true });
11461147
server.on('connection', (socket) => {
11471148

11481149
// If this is special priority
@@ -1162,7 +1163,12 @@ to the event callback function:
11621163
```js
11631164
process.on('message', (m, socket) => {
11641165
if (m === 'socket') {
1165-
socket.end(`Request handled with ${process.argv[2]} priority`);
1166+
if (socket) {
1167+
// Check that the client socket exists.
1168+
// It is possible for the socket to be closed between the time it is
1169+
// sent and the time it is received in the child process.
1170+
socket.end(`Request handled with ${process.argv[2]} priority`);
1171+
}
11661172
}
11671173
});
11681174
```
@@ -1172,6 +1178,10 @@ tracking when the socket is destroyed. To indicate this, the `.connections`
11721178
property becomes `null`. It is recommended not to use `.maxConnections` when
11731179
this occurs.
11741180

1181+
It is also recommended that any `'message'` handlers in the child process
1182+
verify that `socket` exists, as the connection may have been closed during the
1183+
time it takes to send the connection to the child.
1184+
11751185
*Note*: This function uses [`JSON.stringify()`][] internally to serialize the
11761186
`message`.
11771187

0 commit comments

Comments
 (0)