Skip to content
Myr

ipc.md

This file

Path

docs/ipc.md

54 lines · 2.3 KiB · Markdown

Last changed by

Add user guides (#989)ehmickybefore adoptionbe91ecf

History of this file

Take it

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1–54why, 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 messages1011When the [`ipc`](../readme.md#optionsipc) option is `true`, the current process and subprocess can exchange messages. This only works if the subprocess is a Node.js file.1213The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.1415The current process sends messages with [`subprocess.send(message)`](../readme.md#subprocesssendmessage) and receives them with [`subprocess.on('message', (message) => {})`](../readme.md#subprocessonmessage-message--void). The subprocess sends messages with [`process.send(message)`](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback) and [`process.on('message', (message) => {})`](https://nodejs.org/api/process.html#event-message).1617More info on [sending](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [receiving](https://nodejs.org/api/child_process.html#event-message) messages.1819```js20// parent.js21import {execaNode} from 'execa';2223const subprocess = execaNode`child.js`;24subprocess.on('message', messageFromChild => {25 /* ... */26});27subprocess.send('Hello from parent');28```2930```js31// child.js32import process from 'node:process';3334process.on('message', messageFromParent => {35 /* ... */36});37process.send('Hello from child');38```3940## Message type4142By 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).4344To limit messages to JSON instead, the [`serialization`](../readme.md#optionsserialization) option can be set to `'json'`.4546```js47const subprocess = execaNode({serialization: 'json'})`child.js`;48```4950<hr>5152[**Next**: 🐛 Debugging](debugging.md)\53[**Previous**: ⏳️ Streams](streams.md)\54[**Top**: Table of contents](../readme.md#documentation)