capypad
0 day streak
javascript / expert
Snippet

Explicit Resource Management with Symbol.dispose

The 'using' keyword, combined with Symbol.dispose, introduces deterministic resource management. It ensures that cleanup logic is executed immediately when the variable goes out of scope, preventing memory leaks or hanging file handles without relying on manual try-finally blocks.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class TempFile {
constructor(path) {
this.path = path;
console.log(`File ${path} opened.`);
}
[Symbol.dispose]() {
console.log(`File ${this.path} closed and deleted.`);
}
}
 
{
using file = new TempFile('test.txt');
// Resource is bound to this block scope
}
// Automatically disposed here
Breakdown
1
using file = new TempFile(...)
Declares a resource that will be automatically disposed at the end of the block.
2
[Symbol.dispose]() { ... }
Defines the standard method called by the engine for synchronous cleanup.