ipc.md
This file
Path
docs/ipc.md
84 lines · 3.3 KiB · Markdown
Last changed by
Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
History of this fileTake it
ipc.md
📞 Inter-process communication
Exchanging messages
When the ipc option is true, the current process and subprocess can exchange messages. This only works if the subprocess is a Node.js file.
The ipc option defaults to true when using execaNode() or the node option.
The current process sends messages with subprocess.sendMessage(message) and receives them with subprocess.getOneMessage(). The subprocess uses sendMessage(message) and getOneMessage() instead.
// parent.js
import {execaNode} from 'execa';
const subprocess = execaNode`child.js`;
console.log(await subprocess.getOneMessage()); // 'Hello from child'
await subprocess.sendMessage('Hello from parent');
// child.js
import {sendMessage, getOneMessage} from 'execa';
await sendMessage('Hello from child');
console.log(await getOneMessage()); // 'Hello from parent'
Listening to messages
subprocess.getOneMessage() and getOneMessage() read a single message. To listen to multiple messages in a row, subprocess.getEachMessage() and getEachMessage() should be used instead.
subprocess.getEachMessage() waits for the subprocess to end (even when using break or return). It throws if the subprocess fails. This means you do not need to await the subprocess' promise.
// parent.js
import {execaNode} from 'execa';
const subprocess = execaNode`child.js`;
await subprocess.sendMessage(0);
// This loop ends when the subprocess exits.
// It throws if the subprocess fails.
for await (const message of subprocess.getEachMessage()) {
console.log(message); // 1, 3, 5, 7, 9
await subprocess.sendMessage(message + 1);
}
// child.js
import {sendMessage, getEachMessage} from 'execa';
// The subprocess exits when hitting `break`
for await (const message of getEachMessage()) {
if (message === 10) {
break
}
console.log(message); // 0, 2, 4, 6, 8
await sendMessage(message + 1);
}
Message type
By default, messages are serialized using structuredClone(). This supports most types including objects, arrays, Error, Date, RegExp, Map, Set, bigint, Uint8Array, and circular references. This throws when passing functions, symbols or promises (including inside an object or array).
To limit messages to JSON instead, the serialization option can be set to 'json'.
const subprocess = execaNode({serialization: 'json'})`child.js`;
Next: 🐛 Debugging
Previous: ⏳️ Streams
Top: Table of contents