Skip to content

process: port on-exit-leak-free to core

Rodrigo Muino Tomonari requested to merge github/fork/H4ad/add-on-exit-leak into main

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 inside process object that wraps the methods of on-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, objand fn, and executes the fn when the exit event is emitted.
    • The fn is a function that will be called with obj registered and the event, which is exit.
  • registerBeforeExit: Accepts two arguments, objand fn, and executes the fn when the beforeExit event is emitted.
    • The fn is a function that will be called with obj registered and the event, which is beforeExit.
  • unregister: Accepts one argument obj 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.

Merge request reports

Loading