@@ -61,6 +61,113 @@ Worker threads inherit non-process-specific options by default. Refer to
6161[ ` Worker constructor options ` ] [ ] to know how to customize worker thread options,
6262specifically ` argv ` and ` execArgv ` options.
6363
64+ ## ` worker.connect(target[, data][, timeout]) `
65+
66+ <!-- YAML
67+ added: REPLACEME
68+ -->
69+
70+ > Stability: 1.1 - Active development
71+
72+ * ` target ` {number} The target thread id.
73+ * ` data ` {any} Any arbitrary, cloneable JavaScript value.
74+ The data will be passed as the second argument to the callback provided in the
75+ target thread via [ ` worker.setConnectionsListener() ` ] [ ] .
76+ * ` timeout ` {number} Time to wait for the communication port to the target thread,
77+ in milliseconds. By default it's ` undefined ` , which means wait forever.
78+ * Returns: {Promise} A promise for a ` MessagePort ` .
79+
80+ Establishes a connection to another worker thread in the same process, returning a
81+ ` MessagePort ` that can be used for the communication.
82+
83+ The target thread must have a connection listener setup via [ ` worker.setConnectionsListener() ` ] [ ]
84+ otherwise the connection request will fail.
85+
86+ This method should be used when the target thread is not the direct parent or children of the current thread.
87+ The example below creates 10 nested threads, the last one will try to communicate with the third one.
88+
89+ ``` mjs
90+ import { fileURLToPath } from ' node:url' ;
91+ import {
92+ Worker ,
93+ connect ,
94+ setConnectionsListener ,
95+ threadId ,
96+ workerData ,
97+ } from ' node:worker_threads' ;
98+
99+ const level = workerData? .level ?? 0 ;
100+ const targetThread =
101+ workerData? .targetThread ?? (level === 2 ? threadId : undefined );
102+
103+ if (level < 10 ) {
104+ const worker = new Worker (fileURLToPath (import .meta.url), {
105+ workerData : { level : level + 1, targetThread },
106+ });
107+ }
108+
109+ if (level === 2 ) {
110+ setConnectionsListener ((sender , port , data ) => {
111+ port .on (' message' , (message ) => {
112+ console .log (` ${ sender} -> ${ threadId} ` , message);
113+ port .postMessage ({ message: ' pong' , data });
114+ });
115+
116+ return true ;
117+ });
118+ } else if (level === 10 ) {
119+ const port = await connect (targetThread, { foo: ' bar' });
120+
121+ port .on (' message' , (message ) => {
122+ console .log (` ${ targetThread} -> ${ threadId} ` , message);
123+ port .close ();
124+ });
125+
126+ port .postMessage ({ message: ' ping' });
127+ }
128+ ` ` `
129+
130+ ` ` ` cjs
131+ const {
132+ Worker ,
133+ connect ,
134+ setConnectionsListener ,
135+ threadId ,
136+ workerData ,
137+ } = require (' node:worker_threads' );
138+
139+ const level = workerData? .level ?? 0 ;
140+ const targetThread =
141+ workerData? .targetThread ?? (level === 2 ? threadId : undefined );
142+
143+ if (level < 10 ) {
144+ const worker = new Worker (__filename , {
145+ workerData: { level: level + 1 , targetThread },
146+ });
147+ }
148+
149+ if (level === 2 ) {
150+ setConnectionsListener ((sender , port , data ) => {
151+ port .on (' message' , (message ) => {
152+ console .log (` ${ sender} -> ${ threadId} ` , message);
153+ port .postMessage ({ message: ' pong' , data });
154+ });
155+
156+ return true ;
157+ });
158+ } else if (level === 10 ) {
159+ connect (targetThread, { foo: ' bar' }).then ((port ) => {
160+ port .on (' message' , (message ) => {
161+ console .log (` ${ targetThread} -> ${ threadId} ` , message);
162+ port .close ();
163+ });
164+
165+ port .postMessage ({ message: ' ping' });
166+
167+ });
168+ }
169+ ` ` `
170+
64171## ` worker .getEnvironmentData (key)`
65172
66173<!-- YAML
@@ -325,6 +432,32 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
325432 });
326433` ` `
327434
435+ ## ` worker .setConnectionsListener (fn)`
436+
437+ <!-- YAML
438+ added: REPLACEME
439+ -->
440+
441+ > Stability: 1.1 - Active development
442+
443+ * ` fn` {Function} A callback to be executed when [` worker .connect ()` ][] is called from another thread.
444+ The function will receive the following arguments:
445+
446+ * ` sender` {number} The other thread id.
447+ * ` port` {MessagePort} The port than can be used to communicate with the other thread.
448+ * ` data` {any} The data passed as second argument to [` worker .connect ()` ][].
449+
450+ The function must return ` true ` to accept the connection or any other value to
451+ refuse the connection. If the function returns a ` Promise ` , it will be awaited.
452+
453+ Sets the callback that handles connection from other worker threads in the same process.
454+ If the callback is ` null ` or ` undefined ` then the current listener is removed.
455+
456+ When no listeners are present (the default) all connection requests are immediately
457+ refused.
458+
459+ See the example in [` worker .connect ()` ][] for more info on how to use this function and its callback.
460+
328461## ` worker .setEnvironmentData (key[, value])`
329462
330463<!-- YAML
@@ -1437,8 +1570,10 @@ thread spawned will spawn another until the application crashes.
14371570[` v8.getHeapSnapshot()` ]: v8 .md #v8getheapsnapshotoptions
14381571[` vm` ]: vm .md
14391572[` worker.SHARE_ENV` ]: #workershare_env
1573+ [` worker.connect()` ]: #workerconnecttarget- data- timeout
14401574[` worker.on('message')` ]: #event - message_1
14411575[` worker.postMessage()` ]: #workerpostmessagevalue- transferlist
1576+ [` worker.setConnectionsListener()` ]: #workersetconnectionslistenerfn
14421577[` worker.terminate()` ]: #workerterminate
14431578[` worker.threadId` ]: #workerthreadid_1
14441579[async - resource- worker- pool]: async_context .md #using- asyncresource- for - a- worker- thread- pool
0 commit comments