Messages
Piscina allows workers to send messages back to the main thread using the parentPort.postMessage()
method. This can be useful for sending progress updates, or intermediate results during the execution of a long-running task.
- Javascript
- Typescript
index.js
'use strict';
const Piscina = require('piscina');
const { resolve } = require('path');
const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js')
});
(async function () {
piscina.on('message', (event) => {
console.log('Message received from worker: ', event);
});
await piscina.run();
})();
index.ts
import Piscina from "piscina";
import { resolve } from "path";
import { filename } from "./worker";
import { TransferListItem } from "piscina/dist/types";
const piscina = new Piscina({
filename: resolve(__dirname, "./workerWrapper.js"),
workerData: { fullpath: filename },
});
(async function () {
piscina.on('message', (event: string) => {
console.log('Message received from worker: ', event);
});
await piscina.run({});
})();
workerWrapper.js
const { workerData } = require('worker_threads');
if (workerData.fullpath.endsWith(".ts")) {
require("ts-node").register();
}
module.exports = require(workerData.fullpath);
- Javascript
- Typescript
worker.js
'use strict';
const { parentPort } = require('worker_threads');
module.exports = () => {
parentPort.postMessage('hello from the worker pool');
};
worker.ts
import { parentPort } from 'worker_threads';
export default (): void => {
parentPort?.postMessage('hello from the worker pool');
};
You can also check out this example on github.