开发者社区> 镜像站> NPM> kill-worker
kill-worker
Gracefully kill a worker, making sure it terminates in either case.
Last updated 6 months ago by thlorenz .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install kill-worker 
SYNC missed versions from official npm registry.

kill-worker

Gracefully kill a worker, making sure it terminates in either case.

// worker.js
const { parentPort } = require('worker_threads')
parentPort.on('message', (msg) => {
  switch (msg.kind) {
    case 'TERM': {
      return process.exit(0)
    }
    case 'WORK': {
      console.log('normally would do some work here')
      break
    }
    default:
      throw new Error(msg.kind)
  }
})

// main.js
import killWorker from 'kill-worker'
const worker = new Worker('/path/to/worker.js')

// ... after we don't need the worker anymore
try {
  // exit code is always 0 here
  const exitCode = await killWorker(worker, { kind: 'TERM' })
} catch (err) {
  // exit code is always non-zero here and included in the error message
}

Installation

npm install kill-worker

API

/**
 * Kills a worker.
 * First gracefully by sending the provided message so it can exit itself
 * via `process.exit`.
 * If worker doesn't comply and exit within the given `timeoutMs` it is terminated
 * via `worker.terminate`.
 *
 * @param worker the worker to kill
 * @param killMsg the message to send to the worker to comply and exit itself
 * @param timeoutMs timeout in milliseconds after which worker is forcefully terminated
 * @return a promise which resolves if worker exits non-zero and rejects if worker exits
 * non-zero. When worker needs to be terminated the exit code will be non-zero as well.
 */
function killWorker(
  worker: Worker,
  killMsg: any,
  timeoutMs: number = 1e3
): Promise<number>

License

MIT

Current Tags

  • 0.1.1                                ...           latest (6 months ago)

2 Versions

  • 0.1.1                                ...           6 months ago
  • 0.1.0                                ...           6 months ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dev Dependencies (7)
Dependents (0)
None