Usage in Deno
import { ChildProcess } from "node:child_process";
ChildProcess.prototype.send(message: Serializable,callback?: (error: Error | null) => void,): boolean
When an IPC channel has been established between the parent and child (
i.e. when using fork), the subprocess.send()
method can
be used to send messages to the child process. When the child process is a
Node.js instance, these messages can be received via the 'message'
event.
The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.
For example, in the parent script:
const cp = require('node:child_process'); const n = cp.fork(`${__dirname}/sub.js`); n.on('message', (m) => { console.log('PARENT got message:', m); }); // Causes the child to print: CHILD got message: { hello: 'world' } n.send({ hello: 'world' });
And then the child script, 'sub.js'
might look like this:
process.on('message', (m) => { console.log('CHILD got message:', m); }); // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } process.send({ foo: 'bar', baz: NaN });
Child Node.js processes will have a process.send()
method of their own
that allows the child to send messages back to the parent.
There is a special case when sending a {cmd: 'NODE_foo'}
message. Messages
containing a NODE_
prefix in the cmd
property are reserved for use within
Node.js core and will not be emitted in the child's 'message'
event. Rather, such messages are emitted using the'internalMessage'
event and are consumed internally by Node.js.
Applications should avoid using such messages or listening for'internalMessage'
events as it is subject to change without notice.
The optional sendHandle
argument that may be passed to subprocess.send()
is
for passing a TCP server or socket object to the child process. The child will
receive the object as the second argument passed to the callback function
registered on the 'message'
event. Any data that is received
and buffered in the socket will not be sent to the child.
The optional callback
is a function that is invoked after the message is
sent but before the child may have received it. The function is called with a
single argument: null
on success, or an Error
object on failure.
If no callback
function is provided and the message cannot be sent, an'error'
event will be emitted by the ChildProcess
object. This can
happen, for instance, when the child process has already exited.
subprocess.send()
will return false
if the channel has closed or when the
backlog of unsent messages exceeds a threshold that makes it unwise to send
more. Otherwise, the method returns true
. The callback
function can be
used to implement flow control.
Example: sending a server object
The sendHandle
argument can be used, for instance, to pass the handle of
a TCP server object to the child process as illustrated in the example below:
const subprocess = require('node:child_process').fork('subprocess.js'); // Open up the server object and send the handle. const server = require('node:net').createServer(); server.on('connection', (socket) => { socket.end('handled by parent'); }); server.listen(1337, () => { subprocess.send('server', server); });
The child would then receive the server object as:
process.on('message', (m, server) => { if (m === 'server') { server.on('connection', (socket) => { socket.end('handled by child'); }); } });
Once the server is now shared between the parent and child, some connections can be handled by the parent and some by the child.
While the example above uses a server created using the node:net
module,node:dgram
module servers use exactly the same workflow with the exceptions of
listening on a 'message'
event instead of 'connection'
and usingserver.bind()
instead of server.listen()
. This is, however, only
supported on Unix platforms.
Example: sending a socket object
Similarly, the sendHandler
argument can be used to pass the handle of a
socket to the child process. The example below spawns two children that each
handle connections with "normal" or "special" priority:
const { fork } = require('node:child_process'); const normal = fork('subprocess.js', ['normal']); const special = fork('subprocess.js', ['special']); // 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('node:net').createServer({ pauseOnConnect: true }); server.on('connection', (socket) => { // If this is special priority... if (socket.remoteAddress === '74.125.127.100') { special.send('socket', socket); return; } // This is normal priority. normal.send('socket', socket); }); server.listen(1337);
The subprocess.js
would receive the socket handle as the second argument
passed to the event callback function:
process.on('message', (m, socket) => { if (m === 'socket') { 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`); } } });
Do not use .maxConnections
on a socket that has been passed to a subprocess.
The parent cannot track when the socket is destroyed.
Any 'message'
handlers in the subprocess should verify that socket
exists,
as the connection may have been closed during the time it takes to send the
connection to the child.
message: Serializable
boolean
ChildProcess.prototype.send(): boolean
message: Serializable
sendHandle: SendHandle
boolean
ChildProcess.prototype.send(message: Serializable,sendHandle?: SendHandle,options?: MessageOptions,callback?: (error: Error | null) => void,): boolean
boolean