Worker Options
Piscina allows you to customize the environment and runtime options for worker threads. You can set environment variables, command-line arguments, and other options for the worker processes.
This is useful when you need to:
- Pass configuration or environment-specific data to workers
- Control Node.js runtime behavior in workers
- Provide initial data to workers without including it in every task
- Javascript
- Typescript
index.js
'use strict';
const Piscina = require('../..');
const { resolve } = require('path');
const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js'),
env: { A: '123' },
argv: ['a', 'b', 'c'],
execArgv: ['--no-warnings'],
workerData: 'ABC'
});
(async function () {
const result = await piscina.run({ a: 4, b: 6 });
console.log(result); // Prints 10
})();
worker.js
'use strict';
const Piscina = require('../..');
const { format } = require('util');
module.exports = ({ a, b }) => {
console.log(`
process.argv: ${process.argv.slice(2)}
process.execArgv: ${process.execArgv}
process.env: ${format({ ...process.env })}
workerData: ${Piscina.workerData}`);
return a + b;
};
index.ts
import { resolve } from 'path';
import Piscina from 'piscina';
import { filename } from './worker';
const piscina = new Piscina({
filename: resolve(__dirname, 'workerWrapper.js'),
workerData: { fullpath: filename },
env: { A: '123' },
argv: ['a', 'b', 'c'],
execArgv: ['--no-warnings'],
});
(async function () {
const result = await piscina.run({ a: 4, b: 6 });
console.log(result); // Prints 10
})();
worker.ts
import Piscina from 'piscina';
import { format } from 'util';
export default ({ a, b }: { a: number, b: number }): number => {
console.log(`
process.argv: ${process.argv.slice(2)}
process.execArgv: ${process.execArgv}
process.env: ${format({ ...process.env })}
workerData: ${Piscina.workerData}`);
return a + b;
};
workerWrapper.js
const { workerData } = require('worker_threads');
if (workerData.fullpath.endsWith(".ts")) {
require("ts-node").register();
}
module.exports = require(workerData.fullpath);
You can also check out this example on github.