# on-exit-leak-free

> Execute a function on exit without leaking memory, allowing all objects to be garbage collected

Latest version **2.1.2** (published 2023-10-03) · MIT license · 0 weekly downloads

## Install

```sh
npm install on-exit-leak-free
pnpm add on-exit-leak-free
yarn add on-exit-leak-free
bun add on-exit-leak-free
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.1.2 |
| Published | 2023-10-03 |
| First published | 2021-07-07 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >=14.0.0 |
| Dependencies | 0 |
| Unpacked size | 9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 145 |
| Author | Matteo Collina |
| Maintainers | matteo.collina |
| Keywords | weak, reference, finalization, registry, process, exit, garbage, collector |

## Links

- npm: https://www.npmjs.com/package/on-exit-leak-free
- Repository: https://github.com/mcollina/on-exit-or-gc
- Homepage: https://github.com/mcollina/on-exit-or-gc#readme
- Issues: https://github.com/mcollina/on-exit-or-gc/issues
- npm.io page: https://npm.io/package/on-exit-leak-free

## Recent versions

- 2.1.2 (latest) — 2023-10-03
- 2.1.1 — 2023-10-02
- 2.1.0 — 2022-06-22
- 2.0.0 — 2022-06-22
- 1.0.0 — 2022-05-31
- 0.2.0 — 2021-07-23
- 0.1.0 — 2021-07-07

## README

# 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'`](https://nodejs.org/api/process.html#event-exit) without leaking memory,
cleaning things up appropriately if the object is garbage collected.

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

## Install

```bash
npm i on-exit-leak-free
```

## Example

```js
'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

---
_Source: https://npm.io/package/on-exit-leak-free · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
