ipc.md
This file
Path
docs/ipc.md
230 lines · 8.5 KiB · Markdown
Last changed by
Fix documentation and types mistakesSindre Sorhusbefore adoption74b854a
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 📞 Inter-process communication
## Exchanging messages
When the [`ipc`](api.md#optionsipc) option is `true`, the current process and subprocess can exchange messages. This only works if the subprocess is a [Node.js file](node.md).
The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.
Please note that unlike `node:child_process` [`spawn()`](https://nodejs.org/api/child_process.html#optionsstdio), the [`stdio` option](api.md#optionsstdio) does not support the `'ipc'` value. Instead, the [`ipc`](api.md#optionsipc) option must be set to `true`.
The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage-sendmessageoptions) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).
The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage-sendmessageoptions) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions). Those are the same methods, but imported directly from the `'execa'` module.
```js// parent.jsimport {execaNode} from 'execa';
const subprocess = execaNode`child.js`;await subprocess.sendMessage('Hello from parent');const message = await subprocess.getOneMessage();console.log(message); // 'Hello from child'await subprocess;```
```js// child.jsimport {getOneMessage, sendMessage} from 'execa';
const message = await getOneMessage(); // 'Hello from parent'const newMessage = message.replace('parent', 'child'); // 'Hello from child'await sendMessage(newMessage);```
## Listening to messages
The methods described above read a single message. On the other hand, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessagegeteachmessageoptions) and [`getEachMessage()`](api.md#geteachmessagegeteachmessageoptions) return an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This should be preferred when listening to multiple messages.
[`subprocess.getEachMessage()`](api.md#subprocessgeteachmessagegeteachmessageoptions) waits for the subprocess to end (even when using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) or [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)). It throws if the subprocess [fails](api.md#result). This means you do not need to `await` the subprocess' [promise](execution.md#result).
```js// parent.jsimport {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);}```
```js// child.jsimport {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);}```
## Filter messages
```jsimport {getOneMessage} from 'execa';
const startMessage = await getOneMessage({ filter: message => message.type === 'start',});```
```jsimport {getEachMessage} from 'execa';
for await (const message of getEachMessage()) { if (message.type === 'start') { // ... }}```
## Ensure messages are received
When a message is sent by one process, the other process must receive it using [`getOneMessage()`](#exchanging-messages), [`getEachMessage()`](#listening-to-messages), or automatically with [`result.ipcOutput`](api.md#resultipcoutput). If not, that message is silently discarded.
If the [`strict: true`](api.md#sendmessageoptionsstrict) option is passed to [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage-sendmessageoptions) or [`sendMessage(message)`](api.md#sendmessagemessage-sendmessageoptions), an error is thrown instead. This helps identifying subtle race conditions like the following example.
```js// main.jsimport {execaNode} from 'execa';
const subprocess = execaNode`build.js`;// This `build` message is receivedawait subprocess.sendMessage('build', {strict: true});// This `lint` message is not received, so it throwsawait subprocess.sendMessage('lint', {strict: true});await subprocess;```
```js// build.jsimport {getOneMessage} from 'execa';
// Receives the 'build' messageconst task = await getOneMessage();// The `lint` message is sent while `runTask()` is ongoing// Therefore the `lint` message is discardedawait runTask(task);
// Does not receive the `lint` message// Without `strict`, this would wait foreverconst secondTask = await getOneMessage();await runTask(secondTask);```
## Retrieve all messages
The [`result.ipcOutput`](api.md#resultipcoutput) array contains all the messages sent by the subprocess. In many situations, this is simpler than using [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessagegeteachmessageoptions).
```js// main.jsimport {execaNode} from 'execa';
const {ipcOutput} = await execaNode`build.js`;console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}```
```js// build.jsimport {sendMessage} from 'execa';
await sendMessage({kind: 'start', timestamp: new Date()});await runBuild();await sendMessage({kind: 'stop', timestamp: new Date()});```
## Send an initial message
The [`ipcInput`](api.md#optionsipcinput) option sends a message to the [Node.js subprocess](node.md) when it starts.
```js// main.jsimport {execaNode} from 'execa';
const ipcInput = [ {task: 'lint', ignore: /test\.js/}, {task: 'copy', files: new Set(['main.js', 'index.js']),}];await execaNode({ipcInput})`build.js`;```
```js// build.jsimport {getOneMessage} from 'execa';
const ipcInput = await getOneMessage();```
## Message type
By default, messages are serialized using [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This supports most types including objects, arrays, `Error`, `Date`, `RegExp`, `Map`, `Set`, `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`](api.md#optionsserialization) option can be set to `'json'`.
```jsimport {execaNode} from 'execa';
await execaNode({serialization: 'json'})`child.js`;```
Objects with a `type` property starting with `execa:ipc:` are reserved for Execa's internal messages, and should not be sent.
## Messages order
The messages are always received in the same order they were sent. Even when sent all at once.
```jsimport {sendMessage} from 'execa';
await Promise.all([ sendMessage('first'), sendMessage('second'), sendMessage('third'),]);```
## Keeping the subprocess alive
By default, the subprocess is kept alive as long as [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessagegeteachmessageoptions) is waiting. This is recommended if you're sure the current process will send a message, as this prevents the subprocess from exiting too early.
However, if you don't know whether a message will be sent, this can leave the subprocess hanging forever. In that case, the [`reference: false`](api.md#geteachmessageoptionsreference) option can be set.
```jsimport {getEachMessage} from 'execa';
// {type: 'gracefulExit'} is sometimes received, but not alwaysfor await (const message of getEachMessage({reference: false})) { if (message.type === 'gracefulExit') { gracefulExit(); }}```
## Debugging
When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).
Also, when the subprocess [failed](errors.md#subprocess-failure), [`error.ipcOutput`](api.md) contains all the messages sent by the subprocess. Those are also shown at the end of the [error message](errors.md#error-message).
<hr>
[**Next**: 🐛 Debugging](debugging.md)\[**Previous**: ⏳️ Streams](streams.md)\[**Top**: Table of contents](../readme.md#documentation)