Skip to content

Commit

Permalink
doc: make socket IPC examples more robust
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
cjihrig authored and MylesBorins committed Oct 25, 2017
1 parent 4030c7e commit a0b3805
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions doc/api/child_process.md
Original file line number Diff line number Diff line change
Expand Up @@ -1052,8 +1052,9 @@ const { fork } = require('child_process');
const normal = fork('subprocess.js', ['normal']);
const special = fork('subprocess.js', ['special']);

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

// If this is special priority
Expand All @@ -1073,7 +1074,12 @@ passed to the event callback function:
```js
process.on('message', (m, socket) => {
if (m === 'socket') {
socket.end(`Request handled with ${process.argv[2]} priority`);
if (socket) {
// Check that the client socket exists.
// It is possible for the socket to be closed between the time it is
// sent and the time it is received in the child process.
socket.end(`Request handled with ${process.argv[2]} priority`);
}
}
});
```
Expand All @@ -1083,6 +1089,10 @@ tracking when the socket is destroyed. To indicate this, the `.connections`
property becomes `null`. It is recommended not to use `.maxConnections` when
this occurs.

It is also recommended that any `'message'` handlers in the child process
verify that `socket` exists, as the connection may have been closed during the
time it takes to send the connection to the child.

*Note: this function uses [`JSON.stringify()`][] internally to serialize the
`message`.*

Expand Down

0 comments on commit a0b3805

Please sign in to comment.