@youneed/cli-middleware-worker
v0.1.0
Published
Worker-thread middleware for @youneed/cli: this.worker.run / .spawn wrap node:worker_threads in a task — offload CPU work, reactive, terminated on shutdown or teardown.
Readme
@youneed/cli-middleware-worker
Worker-thread offloading for @youneed/cli. The middleware adds
this.worker with run (one-shot offload) and spawn (a persistent worker
module), both wrapping node:worker_threads. this.worker.run(fn, data) runs
fn(data, require) on a worker thread and returns a reactive handle
(running/result/error/exited) — the run is a task, so render()
repaints as it progresses, and the runtime terminates the thread on graceful
shutdown (SIGINT/SIGTERM) or teardown. fn is shipped by source, so keep it
self-contained: no closures — pass inputs via data and load modules via the
injected require.
import { Application, Command } from "@youneed/cli";
import { worker } from "@youneed/cli-middleware-worker";
class Hash extends Command("hash <file>", { middleware: [worker()] }) {
async execute(file: string) {
const job = this.worker.run((path, require) => {
const { readFileSync } = require("node:fs");
const { createHash } = require("node:crypto");
return createHash("sha256").update(readFileSync(path)).digest("hex");
}, file);
console.log(await job.exited); // resolves with the digest (undefined on error)
}
}
const app = Application({ name: "tool", commands: [Hash] });
app.run(["hash", "./package.json"]);Exports
worker()— middleware. Contributesthis.worker, aWorkerApi.
API
WorkerApirun(fn, data?)→WorkerHandle<R>— runsfn(data, require)on a worker thread.dataand the result must be structured-cloneable.spawn(entry, opts?)→WorkerInstance— runs a worker module (file or URL) for message-passing / persistent work.
WorkerHandle<T>—{ running, result?, error?, exited, terminate() }.exitedresolves with the result and never rejects (undefinedon error);using h = this.worker.run(...)terminates on scope exit (Symbol.dispose).WorkerInstance—{ running, postMessage(msg), onMessage(handler), terminate(), exited }.onMessagereturns an unsubscribe;exitedresolves with the worker's exit code. AlsoSymbol.dispose.
