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 fileTake it
Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1–10why, one step back1<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 messages10Add `ipcInput` option (#1068)ehmickybefore adoption46cae30
line 11why, one step back11When 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 back1213The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.14Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10
line 15why, one step back15The 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 back16Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10
line 17why, one step back17The 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 back18Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
lines 19–21why, one step back19```js20// parent.js21import {execaNode} from 'execa';Add user guides (#989)ehmickybefore adoptionbe91ecf
line 22why, one step back22Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 23why, one step back23const subprocess = execaNode`child.js`;Debounce `message` events (#1087)ehmickybefore adoptione8bab97
lines 24–25why, one step back24await subprocess.sendMessage('Hello from parent');25const message = await subprocess.getOneMessage();Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6
line 26why, one step back26console.log(message); // 'Hello from child'Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10
line 27why, one step back27await subprocess;Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
lines 28–29why, one step back28```29Add user guides (#989)ehmickybefore adoptionbe91ecf
line 30why, one step back30```jsAdd promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 31why, one step back31// child.jsAdd `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6
line 32why, one step back32import {getOneMessage, sendMessage} from 'execa';Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 33why, one step back33Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6
lines 34–36why, one step back34const 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 back37```3839## Listening to messages40Fix broken Markdown links (#1119)ehmickybefore adoption8572eb1
line 41why, one step back41The 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 back42Fix broken Markdown links (#1119)ehmickybefore adoption8572eb1
line 43why, one step back43[`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 back4445```jsAdd user guides (#989)ehmickybefore adoptionbe91ecf
lines 46–49why, one step back46// parent.js47import {execaNode} from 'execa';4849const subprocess = execaNode`child.js`;Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
lines 50–57why, one step back50await 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 back58```5960```js61// child.jsAdd promise-based IPC (#1059)ehmickybefore adoptionacc2b68
line 62why, one step back62import {sendMessage, getEachMessage} from 'execa';Add user guides (#989)ehmickybefore adoptionbe91ecf
line 63why, one step back63Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
lines 64–66why, one step back64// 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 back67 break;Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
lines 68–72why, one step back68 }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 back73```74Add `filter` option to `getOneMessage()` (#1076)ehmickybefore adoption571e052
lines 75–94why, one step back75## Filter messages7677```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```94Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10
lines 95–128why, one step back95## Ensure messages are received9697When 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```128Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de
lines 129–130why, one step back129## Retrieve all messages130Fix broken Markdown links (#1119)ehmickybefore adoption8572eb1
line 131why, one step back131The [`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 back132133```js134// main.js135import {execaNode} from 'execa';136Rename `result.ipc` to `result.ipcOutput` (#1075)ehmickybefore adoptionae9b360
lines 137–139why, one step back137const {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 back140```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 back149```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 back171```172Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 173–176why, one step back173## Message type174175By 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).176Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 177why, one step back177To 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 back178179```jsAdd `filter` option to `getOneMessage()` (#1076)ehmickybefore adoption571e052
lines 180–181why, one step back180import {execaNode} from 'execa';181Add `strict` option to `sendMessage()` (#1098)ehmickybefore adoptione085b10
line 182why, one step back182await execaNode({serialization: 'json'})`child.js`;Add user guides (#989)ehmickybefore adoptionbe91ecf
line 183why, one step back183```Add `result.ipc`/`error.ipc` (#1067)ehmickybefore adoption3ab34de
line 184why, one step back184Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6
lines 185–186why, one step back185## Messages order186Debounce `message` events (#1087)ehmickybefore adoptione8bab97
line 187why, one step back187The 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 back188Improve IPC documentation (#1079)ehmickybefore adoption4414737
line 189why, one step back189```jsDebounce `message` events (#1087)ehmickybefore adoptione8bab97
line 190why, one step back190import {sendMessage} from 'execa';Improve IPC documentation (#1079)ehmickybefore adoption4414737
line 191why, one step back191Debounce `message` events (#1087)ehmickybefore adoptione8bab97
lines 192–196why, one step back192await Promise.all([193 sendMessage('first'),194 sendMessage('second'),195 sendMessage('third'),196]);Improve IPC documentation (#1079)ehmickybefore adoption4414737
lines 197–198why, one step back197```198Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)ehmickybefore adoptionff02af6
lines 199–208why, one step back199## Keeping the subprocess alive200201By 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 alwaysFix typo in IPC documentation (#1121)ehmickybefore adoptione15e516
line 209why, one step back209for await (const message of getEachMessage({reference: false})) {Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)ehmickybefore adoptionff02af6
line 210why, one step back210 if (message.type === 'gracefulExit') {Fix typo in IPC documentation (#1121)ehmickybefore adoptione15e516
line 211why, one step back211 gracefulExit();Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)ehmickybefore adoptionff02af6
lines 212–215why, one step back212 }213}214```215Debounce `message` events (#1087)ehmickybefore adoptione8bab97
line 216why, one step back216## DebuggingImprove IPC documentation (#1079)ehmickybefore adoption4414737
line 217why, one step back217Debounce `message` events (#1087)ehmickybefore adoptione8bab97
line 218why, one step back218When 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 back219Debounce `message` events (#1087)ehmickybefore adoptione8bab97
line 220why, one step back220Also, 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 back221222<hr>223224[**Next**: 🐛 Debugging](debugging.md)\225[**Previous**: ⏳️ Streams](streams.md)\226[**Top**: Table of contents](../readme.md#documentation)