Skip to content
Myr

ipc.md

This file

Path

docs/ipc.md

210 lines · 7.8 KiB · Markdown

Last changed by

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

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

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

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 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–70why, one step back
62// The subprocess exits when hitting `break`
63for await (const message of getEachMessage()) {64 if (message === 10) {65 break66 }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–204why, 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.164165This means if [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessage) is called too late (i.e. after the other process called [`sendMessage()`](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.166167Therefore, listening to messages should always be done early, before the other process sends any message.168169### Prefer `exchangeMessage()` over `sendMessage()` + `getOneMessage()`170171When _first_ sending a message, _then_ receiving a response, the following code should be avoided.172173```js174import {sendMessage, getOneMessage} from 'execa';175176await sendMessage(message);177178// The other process might respond between those two calls179180const response = await getOneMessage();181```182183Indeed, 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.184185Using [`exchangeMessage()`](api.md#exchangemessagemessage-getonemessageoptions) prevents this race condition.186187```js188import {exchangeMessage} from 'execa';189190const response = await exchangeMessage(message);191```192193However please note that, when doing the reverse (_first_ receiving a message, _then_ sending a response), the following code is correct.194195```js196import {sendMessage, getOneMessage} from 'execa';197198const message = await getOneMessage();199200// The other process is just waiting for a response between those two calls.201// So there is no race condition here.202203await sendMessage('response');204```

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 205–210why, one step back
205
206<hr>207208[**Next**: 🐛 Debugging](debugging.md)\209[**Previous**: ⏳️ Streams](streams.md)\210[**Top**: Table of contents](../readme.md#documentation)