Execute a function on exit without leaking memory, allowing all objects to be garbage collected
JavaScript
145
56 commits
updated Apr 28, 2024
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+.
npm i on-exit-leak-free
'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)
})
MIT
465 followers · starred Jun 2022
638 followers · starred Jul 2021
32 followers · starred Jun 2022
46 followers · starred Dec 2023
Execute a function on exit without leaking memory, allowing all objects to be garbage collected
JavaScript
145
56 commits
updated Apr 28, 2024
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+.
npm i on-exit-leak-free
'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)
})
MIT
465 followers · starred Jun 2022
638 followers · starred Jul 2021
32 followers · starred Jun 2022
46 followers · starred Dec 2023