Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mcollina/on-exit-leak-free
Execute a function on exit without leaking memory, allowing all objects to be garbage collected
https://github.com/mcollina/on-exit-leak-free
Last synced: 13 days ago
JSON representation
Execute a function on exit without leaking memory, allowing all objects to be garbage collected
- Host: GitHub
- URL: https://github.com/mcollina/on-exit-leak-free
- Owner: mcollina
- License: mit
- Created: 2021-07-05T20:08:42.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-04-28T12:54:29.000Z (7 months ago)
- Last Synced: 2024-10-19T16:39:09.912Z (23 days ago)
- Language: JavaScript
- Size: 52.7 KB
- Stars: 141
- Watchers: 3
- Forks: 6
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
- Security: SECURITY.md
Awesome Lists containing this project
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