on-exit-leak-free

2.1.2 • Public • Published

on-exit-leak-free

This module helps dispose of an object gracefully when the Node.js process exits. It executes a function with a given parameter on 'exit' without leaking memory, cleaning things up appropriately if the object is garbage collected.

Requires WeakRef and FinalizationRegistry, i.e. use Node v14+.

Install

npm i on-exit-leak-free

Example

'use strict'

const { register, unregister } = require('on-exit-leak-free')
const assert = require('assert')

function setup () {
  // This object can be safely garbage collected,
  // and the resulting shutdown function will not be called.
  // There are no leaks.
  const obj = { foo: 'bar' }
  register(obj, shutdown)
  // use registerBeforeExit(obj, shutdown) to execute the function only
  // on beforeExit
  // call unregister(obj) to remove
}

let shutdownCalled = false

// Please make sure that the function passed to register()
// does not create a closure around unnecessary objects.
function shutdown (obj, eventName) {
  console.log(eventName) // beforeExit
  shutdownCalled = true
  assert.strictEqual(obj.foo, 'bar')
}

setup()

process.on('exit', function () {
  assert.strictEqual(shutdownCalled, true)
})

License

MIT

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 2.1.2
    2,643,595
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 2.1.2
    2,643,595
  • 2.1.1
    3,617
  • 2.1.0
    1,270,491
  • 2.0.0
    3
  • 1.0.0
    57,320
  • 0.2.0
    998,587
  • 0.1.0
    129

Package Sidebar

Install

npm i on-exit-leak-free

Weekly Downloads

4,973,742

Version

2.1.2

License

MIT

Unpacked Size

9.25 kB

Total Files

12

Last publish

Collaborators

  • matteo.collina