Skip to content
Myr

ipc.md

This file

Path

docs/ipc.md

244 lines · 9.4 KiB · Markdown

Last changed by

Improve IPC documentation (#1079)ehmickybefore adoption4414737

History of this file

Take it

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1–10why, one step back
1<picture>
2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 📞 Inter-process communication89## Exchanging messages10

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

line 11why, one step back
11When 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).

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 12–14why, one step back
12
13The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.14

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

line 15why, one step back
15The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions). [`subprocess.exchangeMessage(message)`](api.md#subprocessexchangemessagemessage-getonemessageoptions) combines both: first it sends a message, then it returns the response.

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 16why, one step back
16

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 17–18why, one step back
17The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) and [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) instead. Those are the same methods, but imported directly from the `'execa'` module.
18

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 19–21why, one step back
19```js
20// parent.js21import {execaNode} from 'execa';

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 22why, one step back
22

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 23why, one step back
23const subprocess = execaNode`child.js`;

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 24–25why, one step back
24const message = await subprocess.exchangeMessage('Hello from parent');
25console.log(message); // 'Hello from child'

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 26–27why, one step back
26```
27

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 28why, one step back
28```js

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 29why, one step back
29// child.js

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

line 30why, one step back
30import {getOneMessage, sendMessage} from 'execa';

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 31why, one step back
31

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 32–34why, one step back
32const message = await getOneMessage(); // 'Hello from parent'
33const newMessage = message.replace('parent', 'child'); // 'Hello from child'34await sendMessage(newMessage);

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 35–38why, one step back
35```
3637## Listening to messages38

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 39why, one step back
39The methods described above read a single message. On the other hand, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) 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](#prefer-geteachmessage-over-multiple-getonemessage) when listening to multiple messages.

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 40–43why, one step back
40
41[`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) 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).4243```js

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 44–47why, one step back
44// parent.js
45import {execaNode} from 'execa';4647const subprocess = execaNode`child.js`;

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 48–55why, one step back
48await subprocess.sendMessage(0);
4950// This loop ends when the subprocess exits.51// It throws if the subprocess fails.52for await (const message of subprocess.getEachMessage()) {53 console.log(message); // 1, 3, 5, 7, 954 await subprocess.sendMessage(message + 1);55}

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 56–59why, one step back
56```
5758```js59// child.js

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 60why, one step back
60import {sendMessage, getEachMessage} from 'execa';

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 61why, one step back
61

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 62–64why, one step back
62// The subprocess exits when hitting `break`
63for await (const message of getEachMessage()) {64 if (message === 10) {

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 65why, one step back
65 break;

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 66–70why, one step back
66 }
6768 console.log(message); // 0, 2, 4, 6, 869 await sendMessage(message + 1);70}

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 71–72why, one step back
71```
72

Add `filter` option to `getOneMessage()` (#1076)ehmickybefore adoption571e052

lines 73–92why, one step back
73## Filter messages
7475```js76import {getOneMessage} from 'execa';7778const startMessage = await getOneMessage({79 filter: message => message.type === 'start',80});81```8283```js84import {getEachMessage} from 'execa';8586for await (const message of getEachMessage()) {87 if (message.type === 'start') {88 // ...89 }90}91```92

Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de

lines 93–94why, one step back
93## Retrieve all messages
94

Add `filter` option to `getOneMessage()` (#1076)ehmickybefore adoption571e052

line 95why, one step back
95The [`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#subprocessgeteachmessage).

Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de

lines 96–100why, one step back
96
97```js98// main.js99import {execaNode} from 'execa';100

Rename `result.ipc` to `result.ipcOutput` (#1075)ehmickybefore adoptionae9b360

lines 101–103why, one step back
101const {ipcOutput} = await execaNode`build.js`;
102console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}103console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}

Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de

lines 104–112why, one step back
104```
105106```js107// build.js108import {sendMessage} from 'execa';109110await sendMessage({kind: 'start', timestamp: new Date()});111await runBuild();112await sendMessage({kind: 'stop', timestamp: new Date()});

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 113–134why, one step back
113```
114115## Send an initial message116117The [`ipcInput`](api.md#optionsipcinput) option sends a message to the [Node.js subprocess](node.md) when it starts.118119```js120// main.js121import {execaNode} from 'execa';122123const ipcInput = [124 {task: 'lint', ignore: /test\.js/},125 {task: 'copy', files: new Set(['main.js', 'index.js']),126}];127await execaNode({ipcInput})`build.js`;128```129130```js131// build.js132import {getOneMessage} from 'execa';133134const ipcInput = await getOneMessage();

Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de

lines 135–136why, one step back
135```
136

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 137–140why, one step back
137## Message type
138139By 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`, `bigint`, `Uint8Array`, and circular references. This throws when passing functions, symbols or promises (including inside an object or array).140

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 141why, one step back
141To limit messages to JSON instead, the [`serialization`](api.md#optionsserialization) option can be set to `'json'`.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 142–143why, one step back
142
143```js

Add `filter` option to `getOneMessage()` (#1076)ehmickybefore adoption571e052

lines 144–145why, one step back
144import {execaNode} from 'execa';
145

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 146–147why, one step back
146const subprocess = execaNode({serialization: 'json'})`child.js`;
147```

Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de

line 148why, one step back
148

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 149–152why, one step back
149## Messages order
150151The messages are always received in the same order they were sent.152

Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de

lines 153–156why, one step back
153## Debugging
154155When 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).156

Rename `result.ipc` to `result.ipcOutput` (#1075)ehmickybefore adoptionae9b360

line 157why, one step back
157Also, 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).

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 158–164why, one step back
158
159## Best practices160161### Call `getOneMessage()`/`getEachMessage()` early162163If a process sends a message but the other process is not listening/receiving it, that message is silently ignored.164

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 165why, one step back
165This means if [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessage) is called too late (i.e. after the other process called [`sendMessage(message)`](api.md#sendmessagemessage)), it will miss the message. Also, it will keep waiting for the missed message, which might either make it hang forever, or throw when the other process exits.

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 166–168why, one step back
166
167Therefore, listening to messages should always be done early, before the other process sends any message.168

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 169why, one step back
169### First `getOneMessage()` call

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

line 170why, one step back
170

Improve IPC documentation (#1079)ehmickybefore adoption4414737

lines 171–204why, one step back
171On the other hand, the _very first_ call to [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage) or [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) never misses any message. That's because, when a subprocess is just starting, any message sent to it is buffered.
172173This allows the current process to call [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) right after spawning the subprocess, even if it is still initializing.174175```js176// parent.js177import {execaNode} from 'execa';178179const subprocess = execaNode`child.js`;180await subprocess.sendMessage('Hello');181await subprocess.sendMessage('world');182```183184```js185// child.js186import {getOneMessage} from 'execa';187188// This always retrieves the first message.189// Even if `sendMessage()` was called while the subprocess was still initializing.190const helloMessage = await getOneMessage();191192// But this might miss the second message, and hang forever.193// That's because it is not the first call to `getOneMessage()`.194const worldMessage = await getOneMessage();195```196197### Prefer `getEachMessage()` over multiple `getOneMessage()`198199If you call [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) multiple times (like the example above) and the other process sends any message in between those calls, that message [will be missed](#call-getonemessagegeteachmessage-early).200201This can be prevented by using [`getEachMessage()`](api.md#geteachmessage) instead.202203### Prefer `exchangeMessage(message)` over `sendMessage(message)` + `getOneMessage()`204

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 205–218why, one step back
205When _first_ sending a message, _then_ receiving a response, the following code should be avoided.
206207```js208import {sendMessage, getOneMessage} from 'execa';209210await sendMessage(message);211212// The other process might respond between those two calls213214const response = await getOneMessage();215```216217Indeed, when [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) is called, the other process might have already sent a response. This only happens when the other process is very fast. However, when it does happen, `getOneMessage()` will miss that response.218

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 219why, one step back
219Using [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) prevents this race condition.

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 220–238why, one step back
220
221```js222import {exchangeMessage} from 'execa';223224const response = await exchangeMessage(message);225```226227However please note that, when doing the reverse (_first_ receiving a message, _then_ sending a response), the following code is correct.228229```js230import {sendMessage, getOneMessage} from 'execa';231232const message = await getOneMessage();233234// The other process is just waiting for a response between those two calls.235// So there is no race condition here.236237await sendMessage('response');238```

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 239–244why, one step back
239
240<hr>241242[**Next**: 🐛 Debugging](debugging.md)\243[**Previous**: ⏳️ Streams](streams.md)\244[**Top**: Table of contents](../readme.md#documentation)