Skip to main content

Message Port

Worker threads can receive MessagePort objects, enabling direct communication channels with the main thread. This feature is useful for scenarios that require continuous communication or transfer of large data sets between threads.

The example below shows how to use MessagePort with Piscina.

index.js
'use strict';

const Piscina = require('piscina');
const { resolve } = require('path');
const { MessageChannel } = require('worker_threads');

const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js')
});

(async function () {
const channel = new MessageChannel();
channel.port2.on('message', (message) => {
console.log(message);
channel.port2.close();
});
await piscina.run({ port: channel.port1 }, { transferList: [channel.port1] });
})();

The worker file receives the MessagePort and uses it to send a message back to the main thread:

worker.js
'use strict';

module.exports = ({ port }) => {
port.postMessage('hello from the worker pool');
};

You can also check out this example on github.