Problem
Let's first look at a few examples of resources that need to be managed:
-
File handles: A file handle is used to read and write bytes in a file. When you are done with it, you must call
fileHandle.close(), otherwise the file will remain open, even when the JS object is no longer accessible. As the linked Node.js docs say:If a
<FileHandle>is not closed using thefileHandle.close()method, it will try to automatically close the file descriptor and emit a process warning, helping to prevent memory leaks. Please do not rely on this behavior because it can be unreliable and the file may not be closed. Instead, always explicitly close<FileHandle>s. Node.js may change this behavior in the future. -
Network connections: Some connections, such as
WebSocketandRTCPeerConnection, need to be closed if no messages are transmitted. Otherwise, the connection remains open, and connection pools are often very limited in size. -
Stream readers: If you don't call
ReadableStreamDefaultReader.releaseLock(), the stream will be locked and does not permit another reader to consume it.
Here is one concrete example, using a readable stream:
const stream = new ReadableStream({
start(controller) {
controller.enqueue("a");
controller.enqueue("b");
controller.enqueue("c");
controller.close();
},
});
async function readUntil(stream, text) {
const reader = stream.getReader();
let chunk = await reader.read();
while (!chunk.done && chunk.value !== text) {
console.log(chunk);
chunk = await reader.read();
}
// We forgot to release the lock here
}
readUntil(stream, "b").then(() => {
const anotherReader = stream.getReader();
// TypeError: ReadableStreamDefaultReader constructor can only
// accept readable streams that are not yet locked to a reader
});
Here, we have a stream that emits three chunks of data. We read from the stream until we find the letter "b". When readUntil returns, the stream is only partially consumed, so we should be able to continue to read from it using another reader. However, we forgot to release the lock, so although reader is no longer available, the stream is still locked and we cannot create another reader.
The solution in this case is straightforward: call reader.releaseLock() at the end of readUntil. But, a few issues still remain:
-
Inconsistency: different resources have different ways to release them. For example, we have
close(),releaseLock(),disconnect(), etc. The pattern does not generalize. -
Error handling: what happens if the
reader.read()call fails? ThenreadUntilwould terminate and never get to thereader.releaseLock()call. We can fix this usingtry...finally:async function readUntil(stream, text) { const reader = stream.getReader(); try { let chunk = await reader.read(); while (!chunk.done && chunk.value !== text) { console.log(chunk); chunk = await reader.read(); } } finally { reader.releaseLock(); } }But you have to remember to do this every time you have some important resource to release.
-
Scoping: in the above example,
readeris already closed when we exit thetry...finallystatement, but it continues to be available in its scope. This means you may accidentally use it after it's closed. -
Multiple resources: if we have two readers on different streams, we have to remember to release both of them. This is a respectable attempt to do so:
const reader1 = stream1.getReader(); const reader2 = stream2.getReader(); try { // do something with reader1 and reader2 } finally { reader1.releaseLock(); reader2.releaseLock(); }However, this introduces more error handling troubles. If
stream2.getReader()throws, thenreader1does not get released; ifreader1.releaseLock()throws an error, thenreader2does not get released. This means we actually have to wrap each resource acquisition-release pair in its owntry...finally:const reader1 = stream1.getReader(); try { const reader2 = stream2.getReader(); try { // do something with reader1 and reader2 } finally { reader2.releaseLock(); } } finally { reader1.releaseLock(); }
You see how a seemingly benign task of calling releaseLock can quickly lead to nested boilerplate code. This is why JavaScript provides integrated language support for resource management.