process: port on-exit-leak-free to core
This PR basically ports on-exit-leak-free to core, in their words:
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.
This module was created by @mcollina, so all the credits for him, I'm just doing the port.
Motivation
This library was proposed to be introduced on core previously on issue #48058 (closed) via the following syntax:
new FinalizationRegistry(fn, {
runOnExit: true
})
But the main arguments against introducing it were:
- By @tniessen: The usage of
FinalizationRegistry
is an anti-pattern, not recommended to close files automatically, and best to avoid when possible (said by the authors of the API) (ref comment) - By @aduh95: Needing a strong motivation, do not change the
FinalizationRegistry
since it is a standard. (ref comment)
To address the arguments above, I made some changes:
- Instead of changing the standard, I introduced
finalization
object insideprocess
object that wraps the methods ofon-exit-leak-free
. - The motivation to push this module started at https://github.com/H4ad/nodejs-logging-proposal/issues/10, where I'm trying to create a proposal to introduce a logging module to core, and this dependency is one of the dependencies that we plan to use in the implementation. Also, the module
on-exit-leak-free
has more than 5M downloads per month, so it's a demanded feature.
APIs Introduced
Now we have three new methods of process.finalization
:
-
register
: Accepts two arguments,obj
andfn
, and executes thefn
when theexit
event is emitted.- The
fn
is a function that will be called withobj
registered and theevent
, which isexit
.
- The
-
registerBeforeExit
: Accepts two arguments,obj
andfn
, and executes thefn
when thebeforeExit
event is emitted.- The
fn
is a function that will be called withobj
registered and theevent
, which isbeforeExit
.
- The
-
unregister
: Accepts one argumentobj
to unregister the object.
About moving away from classes (like aduh said about creating a new one), I think exposing functions was better than creating a class since we want to be able to use/call those methods in any place we want. But I'm open to better API design for these features.
TODO
I will wait for a few folks to manifest about introducing this feature (in the current state) before spending time creating documentation that could be totally changed or not used, so I will keep it as a draft for a couple of days.
-
Update the documentation -
Explain how to use -
Link/Include the comments about "avoid where possible" that were said by the authors of the FinalizationRegistry/WeakRef. -
Include examples of how to use this feature.
-