forked from andywer/threads.js
-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Snippet: Native node:worker_threads example ts/esm #10
Comments
Expanded version:
// runWorker.ts
import { cpus } from 'os'
import { Worker } from 'worker_threads'
import PQueue from 'p-queue'
const queue = new PQueue({ concurrency: cpus().length })
export function runWorker<T>(filenameWithoutExtension: URL, workerData?: unknown): Promise<T> {
return queue.add(async () => {
const worker =
process.env.NODE_ENV === 'test'
? new Worker(new URL(`${filenameWithoutExtension}.ts`), {
workerData,
execArgv: ['--loader', 'ts-node/esm/transpile-only'],
})
: new Worker(new URL(`${filenameWithoutExtension}.js`), { workerData })
const result = await new Promise<T>((resolve, reject) => {
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', code => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
})
return result
})
}
// worker.ts
import { workerData, parentPort } from 'worker_threads'
export type WorkerData = number[]
export type WorkerResult = number
const numbers = workerData as WorkerData
const result: WorkerResult = numbers.reduce((prev, curr) => prev + curr, 0)
parentPort!.postMessage(result)
// index.ts
import type { WorkerData, WorkerResult } from './worker.js'
import { runWorker } from './runWorker.js'
const workerData: WorkerData = [1, 2]
const result = await runWorker<WorkerResult>(
new URL('./worker', import.meta.url),
workerData,
) Source: andywer#434 (comment) |
Very simple worker thread abstraction for ts-node ESM builds. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
index.ts
worker.ts
Source: https://github.com/lynxtaa/threads-ts-node-esm-issue/tree/no-threads
The text was updated successfully, but these errors were encountered: