UNPKG

nodejs-threads

Version:

A very simple functiobn based implementation of node.js worker threads

38 lines (37 loc) 1.54 kB
/** * This function takes in module path and function name and intstantiates a worker thread. * It returns a promise which resolves to the result of the job. * * @param {string} modulePath Path of the module to be loaded in the worker thread. This should either be absolute path or relative to the current working directory. * @param {string} functionName Function name to be executed in the worker thread. Must be a named export in the module specified in modulePath. * @param {object} payload Payload to be passed to the function specified in functionName. * * @author Karan Raina <karanraina1996@gmail.com> * @created 30-DEC-2021 * * @example * * // No need to create a separate file for the worker thread. * * const { runInWorker } = require('nodejs-threads'); * // OR * import { runInWorker } from 'nodejs-threads'; * * // Assume this is the CPU intensive task * const { calculateScore } = './users.service'; * * async function main() { * try { * // Spawn a worker thread like this: * // Does not block the main thread * const result = await runInWorker('./users.service', 'calculateScore', { name: 'Karan' }); * console.log('[PRIMARY] : WORKER EXECUTED WITH ...', result); * } catch (error) { * console.log('[PRIMARY] : ERROR', error); * } * } * * @returns Returns a promise which resolves to the result of the job */ declare const runInWorker: (modulePath: string, functionName: string, payload?: any) => Promise<any>; export default runInWorker;