Module for executing heavy tasks under forked processes in parallel, by providing a {\ttfamily Promise} based interface, minimum overhead, and bound workers.

The module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be {\ttfamily await}\textquotesingle{}ed. Child (worker) methods can either be synchronous or asynchronous.

The module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the {\ttfamily compute\+Worker\+Key} method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a {\ttfamily compute\+Worker\+Key} method because you want {\itshape some} of the tasks to be sticked, you can return {\ttfamily null} from it.

The list of exposed methods can be explicitly provided via the {\ttfamily exposed\+Methods} option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \char`\"{}minimal example\char`\"{} section for a valid one.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13971}{}\doxysection{Install}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13971}

\begin{DoxyCode}{0}
\DoxyCodeLine{\$ yarn add jest-\/worker }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13972}{}\doxysection{Example}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13972}
This example covers the minimal usage\+:\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13973}{}\doxysubsection{File $<$tt$>$parent.\+js$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13973}

\begin{DoxyCode}{0}
\DoxyCodeLine{import JestWorker from 'jest-\/worker';}
\DoxyCodeLine{}
\DoxyCodeLine{async function main() \{}
\DoxyCodeLine{  const worker = new JestWorker(require.resolve('./Worker'));}
\DoxyCodeLine{  const result = await worker.hello('Alice'); // "{}Hello, Alice"{}}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{main(); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13974}{}\doxysubsection{File $<$tt$>$worker.\+js$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13974}

\begin{DoxyCode}{0}
\DoxyCodeLine{export function hello(param) \{}
\DoxyCodeLine{  return 'Hello, ' + param;}
\DoxyCodeLine{\} }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13975}{}\doxysection{Experimental worker}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13975}
Node 10 shipped with \href{https://nodejs.org/api/worker_threads.html}{\texttt{ worker-\/threads}}, a \char`\"{}threading API\char`\"{} that uses Shared\+Array\+Buffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in {\ttfamily jest-\/worker}.

Since {\ttfamily worker\+\_\+threads} are considered experimental in Node, you have to opt-\/in to this behavior by passing {\ttfamily enable\+Worker\+Threads\+: true} when instantiating the worker. While the feature was unflagged in Node 11.\+7.\+0, you\textquotesingle{}ll need to run the Node process with the {\ttfamily -\/-\/experimental-\/worker} flag for Node 10.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13976}{}\doxysection{API}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13976}
The only exposed method is a constructor ({\ttfamily Jest\+Worker}) that is initialized by passing the worker path, plus an options object.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13977}{}\doxysubsection{$<$tt$>$worker\+Path\+: string$<$/tt$>$ (required)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13977}
Node module name or absolute path of the file to be loaded in the child processes. Use {\ttfamily require.\+resolve} to transform a relative path into an absolute one.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13978}{}\doxysubsection{$<$tt$>$options\+: Object$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13978}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13979}{}\doxysubsubsection{$<$tt$>$exposed\+Methods\+: \$\+Read\+Only\+Array$<$string$>$$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13979}
List of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public {\ttfamily Worker} method, or starting with {\ttfamily \+\_\+}. If you use method auto-\/discovery, then these methods will not be exposed, even if they exist.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13980}{}\doxysubsubsection{$<$tt$>$num\+Workers\+: number$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13980}
Amount of workers to spawn. Defaults to the number of CPUs minus 1.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13981}{}\doxysubsubsection{$<$tt$>$max\+Retries\+: number$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13981}
Maximum amount of times that a dead child can be re-\/spawned, per call. Defaults to {\ttfamily 3}, pass {\ttfamily Infinity} to allow endless retries.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13982}{}\doxysubsubsection{$<$tt$>$fork\+Options\+: Object$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13982}
Allow customizing all options passed to {\ttfamily child\+Process.\+fork}. By default, some values are set ({\ttfamily cwd}, {\ttfamily env} and {\ttfamily exec\+Argv}), but you can override them and customize the rest. For a list of valid values, check \href{https://nodejs.org/api/child_process.html\#child_process_child_process_fork_modulepath_args_options}{\texttt{ the Node documentation}}.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13983}{}\doxysubsubsection{$<$tt$>$compute\+Worker\+Key\+: (method\+: string, ...\+args\+: Array$<$any$>$) =$>$ ?string$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13983}
Every time a method exposed via the API is called, {\ttfamily compute\+Worker\+Key} is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making {\ttfamily compute\+Worker\+Key} return the same identifier for all different calls. If you do not want to bind the call to any worker, return {\ttfamily null}.

The callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \char`\"{}bound worker usage\char`\"{} section.

By default, no process is bound to any worker.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13984}{}\doxysubsubsection{$<$tt$>$setup\+Args\+: Array$<$mixed$>$$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13984}
The arguments that will be passed to the {\ttfamily setup} method during initialization.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13985}{}\doxysubsubsection{$<$tt$>$\+Worker\+Pool\+: (worker\+Path\+: string, options?\+: Worker\+Pool\+Options) =$>$ Worker\+Pool\+Interface$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13985}
Provide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.

The arguments that will be passed to the {\ttfamily setup} method during initialization.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13986}{}\doxysubsubsection{$<$tt$>$enable\+Worker\+Threads\+: boolean$<$/tt$>$ (optional)}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13986}
{\ttfamily jest-\/worker} will automatically detect if {\ttfamily worker\+\_\+threads} are available, but will not use them unless passed {\ttfamily enable\+Worker\+Threads\+: true}.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13987}{}\doxysection{Jest\+Worker}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13987}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13988}{}\doxysubsection{Methods}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13988}
The returned {\ttfamily Jest\+Worker} instance has all the exposed methods, plus some additional ones to interact with the workers itself\+:\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13989}{}\doxysubsubsection{$<$tt$>$get\+Stdout()\+: Readable$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13989}
Returns a {\ttfamily Readable\+Stream} where the standard output of all workers is piped. Note that the {\ttfamily silent} option of the child workers must be set to {\ttfamily true} to make it work. This is the default set by {\ttfamily jest-\/worker}, but keep it in mind when overriding options through {\ttfamily fork\+Options}.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13990}{}\doxysubsubsection{$<$tt$>$get\+Stderr()\+: Readable$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13990}
Returns a {\ttfamily Readable\+Stream} where the standard error of all workers is piped. Note that the {\ttfamily silent} option of the child workers must be set to {\ttfamily true} to make it work. This is the default set by {\ttfamily jest-\/worker}, but keep it in mind when overriding options through {\ttfamily fork\+Options}.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13991}{}\doxysubsubsection{$<$tt$>$end()$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13991}
Finishes the workers by killing all workers. No further calls can be done to the {\ttfamily Worker} instance.

Returns a Promise that resolves with {\ttfamily \{ force\+Exited\+: boolean \}} once all workers are dead. If {\ttfamily force\+Exited} is {\ttfamily true}, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.

{\bfseries{Note\+:}}

{\ttfamily await}ing the {\ttfamily end()} Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, {\ttfamily jest-\/worker} may go through multiple stages of force exiting (e.\+g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.

Consider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn\textquotesingle{}t delay the outputs of your program unnecessarily.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13992}{}\doxysubsection{Worker IDs}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13992}
Each worker has a unique id (index that starts with {\ttfamily 1}), which is available inside the worker as {\ttfamily process.\+env.\+JEST\+\_\+\+WORKER\+\_\+\+ID}.\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13993}{}\doxysection{Setting up and tearing down the child process}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13993}
The child process can define two special methods (both of them can be asynchronous)\+:


\begin{DoxyItemize}
\item {\ttfamily setup()}\+: If defined, it\textquotesingle{}s executed before the first call to any method in the child.
\item {\ttfamily teardown()}\+: If defined, it\textquotesingle{}s executed when the farm ends.
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13994}{}\doxysection{More examples}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13994}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13995}{}\doxysubsection{Standard usage}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13995}
This example covers the standard usage\+:\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13996}{}\doxysubsubsection{File $<$tt$>$parent.\+js$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13996}

\begin{DoxyCode}{0}
\DoxyCodeLine{import JestWorker from 'jest-\/worker';}
\DoxyCodeLine{}
\DoxyCodeLine{async function main() \{}
\DoxyCodeLine{  const myWorker = new JestWorker(require.resolve('./Worker'), \{}
\DoxyCodeLine{    exposedMethods: ['foo', 'bar', 'getWorkerId'],}
\DoxyCodeLine{    numWorkers: 4,}
\DoxyCodeLine{  \});}
\DoxyCodeLine{}
\DoxyCodeLine{  console.log(await myWorker.foo('Alice')); // "{}Hello from foo: Alice"{}}
\DoxyCodeLine{  console.log(await myWorker.bar('Bob')); // "{}Hello from bar: Bob"{}}
\DoxyCodeLine{  console.log(await myWorker.getWorkerId()); // "{}3"{} -\/> this message has sent from the 3rd worker}
\DoxyCodeLine{}
\DoxyCodeLine{  const \{forceExited\} = await myWorker.end();}
\DoxyCodeLine{  if (forceExited) \{}
\DoxyCodeLine{    console.error('Workers failed to exit gracefully');}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{main(); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13997}{}\doxysubsubsection{File $<$tt$>$worker.\+js$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13997}

\begin{DoxyCode}{0}
\DoxyCodeLine{export function foo(param) \{}
\DoxyCodeLine{  return 'Hello from foo: ' + param;}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{export function bar(param) \{}
\DoxyCodeLine{  return 'Hello from bar: ' + param;}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{export function getWorkerId() \{}
\DoxyCodeLine{  return process.env.JEST\_WORKER\_ID;}
\DoxyCodeLine{\} }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13998}{}\doxysubsection{Bound worker usage\+:}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13998}
This example covers the usage with a {\ttfamily compute\+Worker\+Key} method\+:\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md13999}{}\doxysubsubsection{File $<$tt$>$parent.\+js$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md13999}

\begin{DoxyCode}{0}
\DoxyCodeLine{import JestWorker from 'jest-\/worker';}
\DoxyCodeLine{}
\DoxyCodeLine{async function main() \{}
\DoxyCodeLine{  const myWorker = new JestWorker(require.resolve('./Worker'), \{}
\DoxyCodeLine{    computeWorkerKey: (method, filename) => filename,}
\DoxyCodeLine{  \});}
\DoxyCodeLine{}
\DoxyCodeLine{  // Transform the given file, within the first available worker.}
\DoxyCodeLine{  console.log(await myWorker.transform('/tmp/foo.js'));}
\DoxyCodeLine{}
\DoxyCodeLine{  // Wait a bit.}
\DoxyCodeLine{  await sleep(10000);}
\DoxyCodeLine{}
\DoxyCodeLine{  // Transform the same file again. Will immediately return because the}
\DoxyCodeLine{  // transformed file is cached in the worker, and `computeWorkerKey` ensures}
\DoxyCodeLine{  // the same worker that processed the file the first time will process it now.}
\DoxyCodeLine{  console.log(await myWorker.transform('/tmp/foo.js'));}
\DoxyCodeLine{}
\DoxyCodeLine{  const \{forceExited\} = await myWorker.end();}
\DoxyCodeLine{  if (forceExited) \{}
\DoxyCodeLine{    console.error('Workers failed to exit gracefully');}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{main(); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_jest_worker_README_autotoc_md14000}{}\doxysubsubsection{File $<$tt$>$worker.\+js$<$/tt$>$}\label{md_sfcode_node_modules_jest_worker_README_autotoc_md14000}

\begin{DoxyCode}{0}
\DoxyCodeLine{import babel from '@babel/core';}
\DoxyCodeLine{}
\DoxyCodeLine{const cache = Object.create(null);}
\DoxyCodeLine{}
\DoxyCodeLine{export function transform(filename) \{}
\DoxyCodeLine{  if (cache[filename]) \{}
\DoxyCodeLine{    return cache[filename];}
\DoxyCodeLine{  \}}
\DoxyCodeLine{}
\DoxyCodeLine{  // jest-\/worker can handle both immediate results and thenables. If a}
\DoxyCodeLine{  // thenable is returned, it will be await'ed until it resolves.}
\DoxyCodeLine{  return babel.transformFileAsync(filename).then(result => \{}
\DoxyCodeLine{    cache[filename] = result;}
\DoxyCodeLine{}
\DoxyCodeLine{    return result;}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\} }

\end{DoxyCode}
 