proctrap

Node.js process exceeding CPU & memory trap

Usage no npm install needed!

<script type="module">
  import proctrap from 'https://cdn.skypack.dev/proctrap';
</script>

README

proctrap

Node.js process exceeding CPU & memory trap

Installation

Via npm:

$ npm install --save proctrap

API

Declaration

var ProcessTrap = require('proctrap');

Constructor

new ProcessTrap(args)

var trap = new ProcessTrap(args);

args is an object that includes:

  • args.duration - the time during which the CPU or memory usage exceeds limitation (default: 5 * 60 * 1000 ms ~ 5 minutes).
  • args.interval - the break time between two checking actions (default 5 * 1000 ms ~ 5 seconds).
  • args.cpuLimit - a limit value of CPU usage in percent (default: 99 ~ 99%).
  • args.memLimit - a limit value of memory usage in byte (default: undefined).
  • args.autostart - a boolean value determines whether trap will be launched automatically or not (default: true).
  • args.onExceeding - an exceeding limit handling function (default: null).
  • args.logger - a logger object that contains has(level) and log(level, ...) methods (default: a built-in simple logger).

This constructor will throw Error objects in the following cases:

  • both args.cpuLimit and args.memLimit are not provided: Error('Criteria not found, one of CPU or Memory limit should be provided').
  • args.duration value is a negative number or not a number: Error('[duration] should be a positive integer or 0').
  • args.interval value is not a number or not a positive number: Error('[interval] should be a positive integer').

Properties

  • trap.enable - a property is used to enable/disable the trap (default: true).

Methods

  • trap.start() - starts the interval checking task. The constructor calls this method automatically by default (excepts the case of autostart is false).
  • trap.stop() - stops the interval checking task and resets the state.

Example

var proctrap = require('proctrap');
// ...
var trap = new proctrap({
  cpuLimit: 90, // => 90%
  memLimit: 100 * 1024 * 1024, // => 100 MB
  duration: 2 * 60 * 1000, // => 2 minutes
  interval: 3 * 1000, // 3 seconds
  onExceeding: function() {
    trap.stop();
    process.exit(2);
  }
});
// ...

License

MIT