Exercise: Resource Leaks
What happens if we don't close a file we opened? Let's take this to the extreme!
Your code in main.ts:
const files = [];
while (true) {
const file = await Deno.open("main.ts");
const fileCount = files.push(file);
console.log(`Pushing... file #${fileCount}`);
}
What do you think this program will output? Will it execute forever?
Scroll to see the answer...
The Deno runtime eventually terminates with this scary-sounding error.
Pushing... file #12787
Pushing... file #12788
Pushing... file #12789
Pushing... file #12790
Pushing... file #12791
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 24, kind: Other, message: "Too many open files" }', cli/fs.rs:87:15
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fatal runtime error: failed to initiate panic, error 5
Abort trap: 6
The operating system has reached a maximum amount of open files and won't let us open anymore. Our program crashes! To solve this, we need to make sure we call Deno.close() after every Deno.open().
Have questions or issues you are encountering? Post your questions in our #deno channel on Discord! (see lecture 2 to join the community)