Skip to content
Myr

ipc.md

This file

Path

docs/ipc.md

226 lines · 8.1 KiB · Markdown

Last changed by

Fix typo in IPC documentation (#1121)ehmickybefore adoptione15e516

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 `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10

line 15why, one step back
15The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage-sendmessageoptions) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 16why, one step back
16

Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10

line 17why, one step back
17The 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.

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

line 18why, one step back
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`;

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

lines 24–25why, one step back
24await subprocess.sendMessage('Hello from parent');
25const message = await subprocess.getOneMessage();

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

line 26why, one step back
26console.log(message); // 'Hello from child'

Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10

line 27why, one step back
27await subprocess;

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 28–29why, one step back
28```
29

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

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

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

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

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 33why, one step back
33

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

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

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 37–40why, one step back
37```
3839## Listening to messages40

Fix broken Markdown links (#1119)ehmickybefore adoption8572eb1

line 41why, one step back
41The 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.

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 42why, one step back
42

Fix broken Markdown links (#1119)ehmickybefore adoption8572eb1

line 43why, one step back
43[`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).

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 44–45why, one step back
44
45```js

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 58–61why, one step back
58```
5960```js61// child.js

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 63why, one step back
63

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

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

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 67why, one step back
67 break;

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 68–72why, one step back
68 }
6970 console.log(message); // 0, 2, 4, 6, 871 await sendMessage(message + 1);72}

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 73–74why, one step back
73```
74

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

lines 75–94why, one step back
75## Filter messages
7677```js78import {getOneMessage} from 'execa';7980const startMessage = await getOneMessage({81 filter: message => message.type === 'start',82});83```8485```js86import {getEachMessage} from 'execa';8788for await (const message of getEachMessage()) {89 if (message.type === 'start') {90 // ...91 }92}93```94

Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10

lines 95–128why, one step back
95## Ensure messages are received
9697When 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.9899If 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.100101```js102// main.js103import {execaNode} from 'execa';104105const subprocess = execaNode`build.js`;106// This `build` message is received107await subprocess.sendMessage('build', {strict: true});108// This `lint` message is not received, so it throws109await subprocess.sendMessage('lint', {strict: true});110await subprocess;111```112113```js114// build.js115import {getOneMessage} from 'execa';116117// Receives the 'build' message118const task = await getOneMessage();119// The `lint` message is sent while `runTask()` is ongoing120// Therefore the `lint` message is discarded121await runTask(task);122123// Does not receive the `lint` message124// Without `strict`, this would wait forever125const secondTask = await getOneMessage();126await runTask(secondTask);127```128

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

lines 129–130why, one step back
129## Retrieve all messages
130

Fix broken Markdown links (#1119)ehmickybefore adoption8572eb1

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

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

lines 132–136why, one step back
132
133```js134// main.js135import {execaNode} from 'execa';136

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

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

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

lines 140–148why, one step back
140```
141142```js143// build.js144import {sendMessage} from 'execa';145146await sendMessage({kind: 'start', timestamp: new Date()});147await runBuild();148await sendMessage({kind: 'stop', timestamp: new Date()});

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 149–170why, one step back
149```
150151## Send an initial message152153The [`ipcInput`](api.md#optionsipcinput) option sends a message to the [Node.js subprocess](node.md) when it starts.154155```js156// main.js157import {execaNode} from 'execa';158159const ipcInput = [160 {task: 'lint', ignore: /test\.js/},161 {task: 'copy', files: new Set(['main.js', 'index.js']),162}];163await execaNode({ipcInput})`build.js`;164```165166```js167// build.js168import {getOneMessage} from 'execa';169170const ipcInput = await getOneMessage();

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

lines 171–172why, one step back
171```
172

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 173–176why, one step back
173## Message type
174175By 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).176

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 178–179why, one step back
178
179```js

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

lines 180–181why, one step back
180import {execaNode} from 'execa';
181

Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10

line 182why, one step back
182await execaNode({serialization: 'json'})`child.js`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 183why, one step back
183```

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

line 184why, one step back
184

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

lines 185–186why, one step back
185## Messages order
186

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

line 187why, one step back
187The messages are always received in the same order they were sent. Even when sent all at once.

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

line 188why, one step back
188

Improve IPC documentation (#1079)ehmickybefore adoption4414737

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

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

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

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 191why, one step back
191

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

lines 192–196why, one step back
192await Promise.all([
193 sendMessage('first'),194 sendMessage('second'),195 sendMessage('third'),196]);

Improve IPC documentation (#1079)ehmickybefore adoption4414737

lines 197–198why, one step back
197```
198

Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)ehmickybefore adoptionff02af6

lines 199–208why, one step back
199## Keeping the subprocess alive
200201By 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.202203However, 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.204205```js206import {getEachMessage} from 'execa';207208// {type: 'gracefulExit'} is sometimes received, but not always

Fix typo in IPC documentation (#1121)ehmickybefore adoptione15e516

line 209why, one step back
209for await (const message of getEachMessage({reference: false})) {

Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)ehmickybefore adoptionff02af6

line 210why, one step back
210 if (message.type === 'gracefulExit') {

Fix typo in IPC documentation (#1121)ehmickybefore adoptione15e516

line 211why, one step back
211 gracefulExit();

Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)ehmickybefore adoptionff02af6

lines 212–215why, one step back
212 }
213}214```215

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

line 216why, one step back
216## Debugging

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 217why, one step back
217

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

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

Improve IPC documentation (#1079)ehmickybefore adoption4414737

line 219why, one step back
219

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

line 220why, one step back
220Also, 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 user guides (#989)ehmickybefore adoptionbe91ecf

lines 221–226why, one step back
221
222<hr>223224[**Next**: 🐛 Debugging](debugging.md)\225[**Previous**: ⏳️ Streams](streams.md)\226[**Top**: Table of contents](../readme.md#documentation)