Skip to content

Last in first out process.atexit(callback) like other languages and proposal-explicit-resource-management #60337

@loynoir

Description

@loynoir

What is the problem this feature will solve?

Brief

process.addListener("exit", callback)

  • It is first-in-first-out
  • It does not align to C last-in-first-out atexit
  • It does not align to Python last-in-first-out atexit
  • It does not like Javascript Stage 3 last-in-first-out Symbol.dispose

Thus, FR:

  • last-in-first-out process.atexit(callback)

Background

https://github.com/loynoir/atexit.js

Many years ago, I think

  • process exit FIFO listener is not a good design
  • process exit listener should be LIFO

But, many years ago, there wasn't well known LIFO within js.

So, I did not open FR.

But things are different now.

https://github.com/tc39/proposal-explicit-resource-management

[Symbol.dispose]() is invoked in the reverse order of their declaration

Thus, I opened feature request.

  • Last in first out process.atexit(callback)

To make process atexit align to Symbol.dispose LIFO design.

console.log("create file 1");
using _file1 = {
  [Symbol.dispose]() {
    console.log("remove file 1");
  },
};

console.log("create file 2");
using _file2 = {
  [Symbol.dispose]() {
    console.log("remove file 2");
  },
};
create file 1
create file 2
remove file 2
remove file 1

Current

console.log("create file 1");
process.addListener("exit", (code) => {
  console.log("remove file 1");
});

console.log("create file 2");
process.addListener("exit", (code) => {
  console.log("remove file 2");
});

process.exit(0);
create file 1
create file 2
remove file 1
remove file 2

What is the feature you are proposing to solve the problem?

After

console.log("create file 1");
process.atexit((code) => {
  console.log("remove file 1");
});

console.log("create file 2");
process.atexit((code) => {
  console.log("remove file 2");
});

process.exit(0);
create file 1
create file 2
remove file 2
remove file 1

What alternatives have you considered?

Prior Art

C

https://en.cppreference.com/w/c/program/atexit

int atexit( void (*func)(void) );

The functions will be called in reverse order they were registered, i.e. the function registered last will be executed first.

Python

https://docs.python.org/3.15/library/atexit.html#module-atexit

atexit.register(func, *args, **kwargs)
atexit.unregister(func)

atexit runs these functions in the reverse order in which they were registered; if you register A, B, and C, at interpreter termination time they will be run in the order C, B, A.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.

    Type

    No type

    Projects

    Status

    Awaiting Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions