subprocess.send(message[, sendHandle[, options]][, callback])


  • message <Object>
  • sendHandle <Handle>
  • options <Object> options 参数(如果存在)是用于参数化某些类型句柄的发送的对象。 options 支持以下属性:
    • keepOpen <boolean> 当传入 net.Socket 实例时可以使用的值。 当为 true 时,套接字在发送过程中保持打开状态。 默认值: false
  • callback <Function>
  • 返回: <boolean>

当父进程和子进程之间建立了 IPC 通道时(即当使用 child_process.fork() 时),可以使用 subprocess.send() 方法向子进程发送消息。 当子进程是 Node.js 实例时,可以通过 'message' 事件接收这些消息。

消息经过序列化和解析。 结果消息可能与最初发送的消息不同。

例如,在父进程脚本中:

const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);

n.on('message', (m) => {
  console.log('PARENT got message:', m);
});

// 引起子进程打印:CHILD got message: { hello: 'world' }
n.send({ hello: 'world' });

然后子进程脚本 'sub.js' 可能如下所示:

process.on('message', (m) => {
  console.log('CHILD got message:', m);
});

// 引起父进程打印:PARENT got message: { foo: 'bar', baz: null }
process.send({ foo: 'bar', baz: NaN });

子 Node.js 进程将拥有自己的 process.send() 方法,允许子进程将消息发送回父进程。

当发送 {cmd: 'NODE_foo'} 消息时是一种特殊情况。 在 cmd 属性中包含 NODE_ 前缀的消息是 Node.js 核心预留使用的,不会在子进程的 'message' 事件中触发。 而是,此类消息使用 'internalMessage' 事件触发,并由 Node.js 在内部使用。 应用程序应避免使用此类消息或监听 'internalMessage' 事件,因为它可能随时更改,恕不另行通知。

可以传给 subprocess.send() 的可选 sendHandle 参数用于将 TCP 服务器或套接字对象传给子进程。 子进程将接收该对象作为传给在 'message' 事件上注册的回调函数的第二个参数。 在套接字中接收和缓冲的任何数据都不会发送给子进程。

可选的 callback 函数将在消息发送之后但在子进程可能接收到它之前调用。 该函数使用单个参数调用:成功时为 null,失败时为 Error 对象。

如果没有提供 callback 函数且无法发送消息,则 ChildProcess 对象将触发 'error' 事件。 例如,当子进程已经退出时,就会发生这种情况。

如果通道已关闭或未发送消息的积压超过阈值(这使得发送更多消息是不明智的),则 subprocess.send() 将返回 false。 否则,该方法返回 truecallback 函数可用于实现流量控制。

  • message <Object>
  • sendHandle <Handle>
  • options <Object> The options argument, if present, is an object used to parameterize the sending of certain types of handles. options supports the following properties:
    • keepOpen <boolean> A value that can be used when passing instances of net.Socket. When true, the socket is kept open in the sending process. Default: false.
  • callback <Function>
  • Returns: <boolean>

When an IPC channel has been established between the parent and child ( i.e. when using child_process.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('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.