Skip to content

Commit

Permalink
Do not initialize FinalizationRegistry if not required (#50)
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Collina <[email protected]>
  • Loading branch information
mcollina authored Oct 3, 2023
1 parent f2f303a commit 7c4712e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
16 changes: 15 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ const functions = {
exit: onExit,
beforeExit: onBeforeExit
}
const registry = new FinalizationRegistry(clear)

let registry

function ensureRegistry () {
if (registry === undefined) {
registry = new FinalizationRegistry(clear)
}
}

function install (event) {
if (refs[event].length > 0) {
Expand All @@ -23,6 +30,9 @@ function uninstall (event) {
return
}
process.removeListener(event, functions[event])
if (refs.exit.length === 0 && refs.beforeExit.length === 0) {
registry = undefined
}
}

function onExit () {
Expand Down Expand Up @@ -64,6 +74,7 @@ function _register (event, obj, fn) {
const ref = new WeakRef(obj)
ref.fn = fn

ensureRegistry()
registry.register(obj, ref)
refs[event].push(ref)
}
Expand All @@ -77,6 +88,9 @@ function registerBeforeExit (obj, fn) {
}

function unregister (obj) {
if (registry === undefined) {
return
}
registry.unregister(obj)
for (const event of ['exit', 'beforeExit']) {
refs[event] = refs[event].filter((ref) => {
Expand Down
1 change: 0 additions & 1 deletion test/fixtures/beforeExit.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ function setup () {
let shutdownCalled = false
let timeoutFinished = false
function shutdown (obj, event) {
console.log(event)
shutdownCalled = true
if (event === 'beforeExit') {
setTimeout(function () {
Expand Down

0 comments on commit 7c4712e

Please sign in to comment.