Closing streams and disposables
suggest changeFiles, sockets, servers, timers and child processes are resources owned by the operating system. The garbage collector frees JavaScript memory, but it doesn't reliably (or promptly) release a file descriptor or stop a server. If you forget to close them, a long-running program eventually fails with EMFILE: too many open files, a test runner never exits, or a file ends up truncated.
Node.js gives you two tools for this:
- the stream API:
end(),destroy(),finished()andpipeline() - explicit resource management:
using/await usingdeclarations,Symbol.dispose/Symbol.asyncDispose, andDisposableStack/AsyncDisposableStack
| Task | API |
|---|---|
| Finish writing and close | writable.end() |
| Abort and close immediately | stream.destroy([err]) |
| Wait until a stream is done and closed | finished() from node:stream/promises |
| Connect streams and close them all on error | pipeline() from node:stream/promises |
| Close a resource at the end of a block | using x = ... / await using x = ... |
| Manage a dynamic number of resources | DisposableStack / AsyncDisposableStack |
The examples are ES modules (save them as .mjs) and were run with Node.js 24. using and await using work without flags starting with Node.js 24.
end() vs destroy()
There are two ways to close a writable stream, and they do very different things.
end() is the normal way: it optionally writes a final chunk, flushes everything still buffered, and then closes the underlying resource. Two events follow: finish when all data has been handed to the OS, and close when the file descriptor is released.
import { createWriteStream } from 'node:fs';
import { readFile, rm } from 'node:fs/promises';
const out = createWriteStream('log.txt');
out.on('finish', () => console.log('finish: all data flushed'));
out.on('close', () => console.log('close: file descriptor released'));
out.write('line 1\n');
out.write('line 2\n');
out.end('last line\n'); // write final chunk, then close
console.log('end() returned, writableEnded =', out.writableEnded);
out.on('close', async () => {
console.log(JSON.stringify(await readFile('log.txt', 'utf8')));
await rm('log.txt');
});
end() returned, writableEnded = true
finish: all data flushed
close: file descriptor released
"line 1\nline 2\nlast line\n"
end() returns immediately. The flushing happens asynchronously, so reading the file right after end() could see incomplete data.
destroy() is the emergency brake. It closes the stream right away and discards anything still buffered. finish is not emitted, and further writes fail:
import { createWriteStream } from 'node:fs';
import { readFile, rm } from 'node:fs/promises';
const out = createWriteStream('log.txt');
out.on('finish', () => console.log('finish'));
out.on('close', async () => {
console.log('close, destroyed =', out.destroyed);
console.log('file contains', JSON.stringify(await readFile('log.txt', 'utf8')));
await rm('log.txt');
});
out.write('this may or may not be written\n');
out.destroy(); // abort immediately, buffered data is discarded
out.write('after destroy', (err) => console.log('write callback:', err.code));
write callback: ERR_STREAM_DESTROYED
close, destroyed = true
file contains ""
Use end() when the work succeeded, and destroy() when it failed or was cancelled. destroy(err) additionally emits error with err before close, which is how a stream reports failure to whoever is consuming it.
Readable streams have no end(). A readable closes itself when all data has been consumed (autoDestroy is on by default). If you stop reading early, call destroy().
Readable streams you stop reading stay open
A readable stream that you abandon halfway keeps its file descriptor open. for await is safer: leaving the loop with break, return or an exception destroys the stream automatically.
import { createReadStream } from 'node:fs';
import { writeFile, rm } from 'node:fs/promises';
await writeFile('big.txt', 'x'.repeat(1024 * 1024));
// 1. Read the first chunk with a listener, then stop: the stream stays open
const a = createReadStream('big.txt', { highWaterMark: 1024 });
a.on('close', () => console.log('a closed'));
a.once('data', (chunk) => {
console.log('a got', chunk.length, 'bytes, pausing');
a.pause();
});
// 2. Same with for await + break: the stream is destroyed for us
const b = createReadStream('big.txt', { highWaterMark: 1024 });
b.on('close', () => console.log('b closed'));
for await (const chunk of b) {
console.log('b got', chunk.length, 'bytes, breaking');
break;
}
setTimeout(async () => {
console.log('a.destroyed =', a.destroyed, ' b.destroyed =', b.destroyed);
a.destroy();
await rm('big.txt');
}, 100);
a got 1024 bytes, pausing
b got 1024 bytes, breaking
b closed
a.destroyed = false b.destroyed = true
a closed
If you want to keep using a stream after leaving a loop, iterate over stream.iterator({ destroyOnReturn: false }) instead of the stream itself.
Waiting until a stream is closed
To know when a stream is really done, use finished() from node:stream/promises. It resolves after the stream has finished and been closed, and rejects if the stream errored or was destroyed prematurely:
import { createWriteStream } from 'node:fs';
import { stat, rm } from 'node:fs/promises';
import { finished } from 'node:stream/promises';
const out = createWriteStream('data.csv');
out.on('finish', () => console.log('event: finish'));
out.on('close', () => console.log('event: close'));
for (let i = 0; i < 1000; i++) {
out.write(`${i},item ${i}\n`);
}
out.end();
await finished(out);
console.log('finished() resolved, closed =', out.closed);
console.log('size:', (await stat('data.csv')).size);
// calling finished() on an already closed stream resolves immediately
await finished(out);
console.log('second finished() resolved too');
await rm('data.csv');
event: finish
event: close
finished() resolved, closed = true
size: 12780
second finished() resolved too
Prefer finished() over once(stream, 'close'). If the stream has already closed by the time you start waiting, the event will never fire again and once() waits forever, while finished() checks the current state.
The try / catch pattern for streams
Putting it together, the classic way to write a file through a stream and clean up properly on failure is:
import { createWriteStream } from 'node:fs';
import { readFile, rm } from 'node:fs/promises';
import { finished } from 'node:stream/promises';
async function exportRows(path, rows) {
const out = createWriteStream(path);
try {
for (const row of rows) {
if (row == null) throw new Error('bad row');
out.write(`${row}\n`);
}
out.end();
await finished(out); // all data is on disk and the fd is closed
} catch (err) {
out.destroy(); // discard buffered data and release the fd
await finished(out).catch(() => {}); // wait until it is really closed
await rm(path, { force: true }); // don't leave a half-written file
throw err;
}
}
await exportRows('rows.txt', ['a', 'b', 'c']);
console.log(JSON.stringify(await readFile('rows.txt', 'utf8')));
try {
await exportRows('rows.txt', ['a', null]);
} catch (err) {
console.log(err.message);
await readFile('rows.txt').catch((e) => console.log(e.code));
}
"a\nb\nc\n"
bad row
ENOENT
pipeline() closes every stream on error
readable.pipe(writable) doesn't propagate errors. If the source fails, the destination is never closed and its file descriptor leaks. pipeline() destroys every stream in the chain when any of them fails, and gives you a single promise to await:
import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';
import { rm } from 'node:fs/promises';
// pipe(): an error in the source does not close the destination
{
const src = createReadStream('missing.txt');
const dst = createWriteStream('out1.gz');
src.on('error', (err) => console.log('pipe: source error', err.code));
src.pipe(createGzip()).pipe(dst);
await new Promise((r) => setTimeout(r, 100));
console.log('pipe: destination destroyed?', dst.destroyed);
dst.destroy(); // we have to do it ourselves
}
// pipeline(): an error anywhere destroys every stream
{
const src = createReadStream('missing.txt');
const gzip = createGzip();
const dst = createWriteStream('out2.gz');
try {
await pipeline(src, gzip, dst);
} catch (err) {
console.log('pipeline: rejected with', err.code);
}
console.log('pipeline: destroyed?', src.destroyed, gzip.destroyed, dst.destroyed);
}
await rm('out1.gz', { force: true });
await rm('out2.gz', { force: true });
pipe: source error ENOENT
pipe: destination destroyed? false
pipeline: rejected with ENOENT
pipeline: destroyed? true true true
In new code, use pipeline() whenever you connect streams. See Piping streams for more about piping.
FileHandle must be closed explicitly
fs/promises.open() returns a FileHandle. If you lose the last reference to it without calling close(), Node.js closes the descriptor during garbage collection, but only at some unpredictable time, and it complains:
import { open } from 'node:fs/promises';
async function leak() {
const fh = await open('e6.mjs');
const { bytesRead } = await fh.read(Buffer.alloc(16), 0, 16, 0);
console.log('read', bytesRead, 'bytes, forgot to close');
}
await leak();
globalThis.gc();
await new Promise((r) => setTimeout(r, 100));
$ node --expose-gc e6.mjs
read 16 bytes, forgot to close
(node:26584) Warning: Closing file descriptor 3 on garbage collection
(Use `node --trace-warnings ...` to show where the warning was created)
(node:26584) [DEP0137] DeprecationWarning: Closing a FileHandle object on garbage collection is deprecated. Please close FileHandle objects explicitly using FileHandle.prototype.close(). In the future, an error will be thrown if a file descriptor is closed during garbage collection.
Closing in finally works, but there is a shorter way.
using and await using
A declaration with using (for synchronous cleanup) or await using (for asynchronous cleanup) binds a value that is disposed automatically when the enclosing block exits: normally, through return, or by an exception.
Disposal calls the object's [Symbol.dispose]() method, or for await using, its [Symbol.asyncDispose]() method (falling back to Symbol.dispose). FileHandle implements Symbol.asyncDispose by calling close():
import { open } from 'node:fs/promises';
let saved;
async function countBytes(path) {
await using fh = await open(path);
saved = fh;
console.log('inside: fd =', fh.fd);
const { size } = await fh.stat();
if (size > 10) throw new Error(`${path} is too big (${size} bytes)`);
return size;
}
try {
await countBytes('words.txt');
} catch (err) {
console.log(err.message);
}
console.log('after: fd =', saved.fd); // -1 means closed
inside: fd = 3
words.txt is too big (17 bytes)
after: fd = -1
This is equivalent to try { ... } finally { await fh.close(); }, without the extra nesting and without the risk of forgetting it.
Rules worth knowing:
usingis allowed inside blocks, functions,forloop heads and at the top level of modules (CommonJS files work too, because Node.js wraps them in a function).await usingadditionally requires an async function or the top level of an ES module.- The binding is constant, like
const. - The value may be
nullorundefined(nothing is disposed). Any other value without a dispose method throws aTypeErrorat the declaration. - Disposing a
FileHandlethat is already closed is harmless. For example,fh.createReadStream()closes the handle itself when the stream ends:
import { open } from 'node:fs/promises';
{
await using fh = await open('words.txt');
const stream = fh.createReadStream({ encoding: 'utf8' });
for await (const chunk of stream) {
console.log(JSON.stringify(chunk));
}
// the stream closed fh itself (autoClose: true is the default)
console.log('fd after stream ended =', fh.fd);
} // disposing an already closed FileHandle is a no-op
console.log('no error');
"alpha\nbeta\ngamma\n"
fd after stream ended = -1
no error
Built-in disposables
Many Node.js objects implement the dispose protocol. In Node.js 24:
| Object | Method | What disposal does |
|---|---|---|
FileHandle (fs/promises.open()) |
Symbol.asyncDispose |
close() |
fs.Dir (opendir()) |
both | close() |
Readable, Writable, Duplex streams |
Symbol.asyncDispose |
destroy() unless already ended, then waits for close |
http.Server, net.Server |
Symbol.asyncDispose |
close() and wait |
Worker |
Symbol.asyncDispose |
terminate() |
Timeout (setTimeout(), setInterval()) |
Symbol.dispose |
clearTimeout() |
ChildProcess |
Symbol.dispose |
kill() (SIGTERM) |
readline.Interface |
Symbol.dispose |
close() |
events.addAbortListener() result |
Symbol.dispose |
removes the listener |
fs.mkdtempDisposable() result |
Symbol.asyncDispose |
removes the directory |
A server, a timer and a child process cleaned up by block scope:
import http from 'node:http';
import { spawn } from 'node:child_process';
{
await using server = http.createServer((req, res) => res.end('hello\n'));
await new Promise((resolve) => server.listen(0, resolve));
server.on('close', () => console.log('server closed'));
const res = await fetch(`http://localhost:${server.address().port}/`);
console.log('response:', (await res.text()).trim());
}
{
using timer = setTimeout(() => console.log('never printed'), 1000);
using child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);
child.on('exit', (code, signal) => console.log('child exited with', signal));
console.log('child pid is a number:', typeof child.pid === 'number');
} // timer is cleared, child is killed
console.log('done, nothing keeps the process alive');
response: hello
server closed
child pid is a number: true
done, nothing keeps the process alive
child exited with SIGTERM
This is especially handy in tests, where a forgotten server or interval keeps the test runner from exiting.
Gotcha: disposing a writable stream discards unfinished data
Look closely at the table above: disposing a stream calls destroy() unless it has already finished. Calling end() is not enough, because end() only starts flushing. If the scope exits before the stream has finished, the buffered data is thrown away:
import { createWriteStream } from 'node:fs';
import { readFile, rm } from 'node:fs/promises';
import { finished } from 'node:stream/promises';
async function writeReport(path, lines, waitForFinish) {
await using out = createWriteStream(path);
for (const line of lines) out.write(line + '\n');
out.end();
if (waitForFinish) await finished(out);
}
const lines = Array.from({ length: 1000 }, (_, i) => `row ${i}`);
await writeReport('a.txt', lines, false);
console.log('without finished():', (await readFile('a.txt', 'utf8')).length, 'chars');
await writeReport('b.txt', lines, true);
console.log('with finished(): ', (await readFile('b.txt', 'utf8')).length, 'chars');
await rm('a.txt');
await rm('b.txt');
without finished(): 0 chars
with finished(): 7890 chars
That is actually a sensible design: if an exception skips the end() / finished() lines, the stream is aborted instead of silently saving a partial file. On the success path, always await finished(out) (or use pipeline()) before leaving the block.
Gotcha: await using and for await on the same readable
for await destroys a readable stream when you break out of it, with an AbortError as the reason. The stream's dispose method then sees a stream that was destroyed with an error and reports that error:
import { createReadStream } from 'node:fs';
try {
await using input = createReadStream('words.txt', { highWaterMark: 4 });
for await (const chunk of input) {
break; // the loop destroys input with an AbortError...
}
} catch (err) {
// ...and the disposer then reports that error
console.log('caught', err.name);
}
caught AbortError
Either rely on for await alone to close the stream (as in the earlier example), or let the disposer own it and iterate with destroyOnReturn: false:
import { createReadStream } from 'node:fs';
async function readHeader(path) {
await using input = createReadStream(path, { encoding: 'utf8', highWaterMark: 4 });
input.on('close', () => console.log('input closed'));
let text = '';
for await (const chunk of input.iterator({ destroyOnReturn: false })) {
text += chunk;
if (text.includes('\n')) break;
}
console.log('leaving readHeader, destroyed =', input.destroyed);
return text.split('\n')[0];
}
console.log('header:', await readHeader('words.txt'));
leaving readHeader, destroyed = false
input closed
header: alpha
Making your own disposables
Any object becomes usable with using by implementing [Symbol.dispose](), or with await using by implementing [Symbol.asyncDispose](). Keep a regular close() method too, for callers that manage lifetime manually, and make it safe to call twice:
import { createWriteStream } from 'node:fs';
import { readFile, rm } from 'node:fs/promises';
import { finished } from 'node:stream/promises';
class LogFile {
#out;
constructor(path) {
this.path = path;
this.#out = createWriteStream(path, { flags: 'a' });
}
log(msg) {
this.#out.write(`${msg}\n`);
}
async close() {
if (this.#out.closed) return; // make close() idempotent
this.#out.end();
await finished(this.#out);
console.log('closed', this.path);
}
async [Symbol.asyncDispose]() {
await this.close();
}
}
{
await using access = new LogFile('access.log');
await using errors = new LogFile('error.log');
access.log('GET /');
errors.log('disk almost full');
access.log('GET /about');
} // errors is disposed first, then access
console.log(await readFile('access.log', 'utf8'));
await rm('access.log');
await rm('error.log');
closed error.log
closed access.log
GET /
GET /about
Resources are disposed in reverse order of declaration, just like nested try / finally blocks unwind. That matters when one resource depends on another, for example a stream that writes through a socket: the stream is declared later, so it is closed first.
The Temporary files article has another example: a temp file that deletes itself on disposal.
When dispose throws: SuppressedError
If the block throws and a dispose method throws too, neither error is lost. They are combined into a SuppressedError: error is the newer error (from disposal) and suppressed is the one it replaced:
const resource = (name, failOnClose) => ({
async [Symbol.asyncDispose]() {
console.log('disposing', name);
if (failOnClose) throw new Error(`${name}: close failed`);
},
});
try {
await using a = resource('a', true);
await using b = resource('b', false);
throw new Error('work failed');
} catch (err) {
console.log(err.constructor.name);
console.log(' error: ', err.error.message);
console.log(' suppressed:', err.suppressed.message);
}
disposing b
disposing a
SuppressedError
error: a: close failed
suppressed: work failed
Note that b was still disposed, and a was disposed even though b's cleanup ran first. One failing cleanup doesn't skip the others. Compare that to a hand-written finally with two await x.close() calls, where an exception from the first skips the second.
If your error handling looks at err.code or instanceof, remember to unwrap SuppressedError.
AsyncDisposableStack for a dynamic number of resources
using declarations work when you know the resources at write time. When you open a variable number of them, collect them in an AsyncDisposableStack (or DisposableStack for synchronous ones) and dispose the stack:
stack.use(value)registers a disposable and returns itstack.adopt(value, onDispose)registers a value that isn't disposable, with a cleanup functionstack.defer(fn)registers a plain cleanup callbackstack.move()transfers all registered resources to a new stack, leaving the old one empty
import { open } from 'node:fs/promises';
async function readAll(paths) {
await using stack = new AsyncDisposableStack();
const handles = [];
for (const path of paths) {
const fh = stack.adopt(await open(path), async (fh) => {
await fh.close();
console.log('closed', path);
});
handles.push(fh);
}
const texts = await Promise.all(handles.map((fh) => fh.readFile('utf8')));
return texts.join('');
}
console.log(JSON.stringify(await readAll(['a.txt', 'b.txt'])));
try {
await readAll(['a.txt', 'b.txt', 'missing.txt']);
} catch (err) {
console.log('error:', err.code);
}
closed b.txt
closed a.txt
"one\ntwo\n"
closed b.txt
closed a.txt
error: ENOENT
When opening missing.txt fails, the two files opened before it are still closed. Writing that correctly by hand takes noticeably more code.
Transferring ownership with move()
A factory that opens several resources has a tricky requirement: if a later step fails, everything opened so far must be closed, but on success the resources must stay open and belong to the returned object. move() handles exactly this:
import { open } from 'node:fs/promises';
class Merger {
#stack;
constructor(stack, inputs, output) {
this.#stack = stack;
this.inputs = inputs;
this.output = output;
}
static async create(inputPaths, outputPath) {
await using stack = new AsyncDisposableStack();
const inputs = [];
for (const p of inputPaths) inputs.push(stack.use(await open(p)));
const output = stack.use(await open(outputPath, 'w'));
// success: hand all resources over to the new object;
// stack is now empty, so disposing it at the end of create() does nothing
return new Merger(stack.move(), inputs, output);
}
async run() {
for (const fh of this.inputs) await this.output.write(await fh.readFile());
}
async [Symbol.asyncDispose]() {
await this.#stack.disposeAsync();
console.log('merger disposed');
}
}
{
await using m = await Merger.create(['a.txt', 'b.txt'], 'merged.txt');
await m.run();
}
try {
await using m = await Merger.create(['a.txt', 'nope.txt'], 'merged.txt');
} catch (err) {
// a.txt was opened, then nope.txt failed: a.txt is closed by create()
console.log('create failed:', err.code);
}
merger disposed
create failed: ENOENT
TypeScript and older Node.js versions
- TypeScript supports
usingandawait usingsince 5.2. Add"esnext.disposable"(or"esnext") tolibintsconfig.json, and@types/nodefor the Node.js-specific dispose methods. - On Node.js 22 and older,
usingis a syntax error. Usetry/finally, or compile the code with TypeScript or Babel, which rewriteusingintotry/finally. Recent Node.js 20 and 22 releases already defineSymbol.dispose/Symbol.asyncDisposeand implement them on many core objects, so transpiledusingcode works there as well.
Summary
- Close a writable with
end()on success anddestroy()on failure; wait withawait finished(stream). - Readables close themselves when fully consumed. If you stop early,
destroy()them, or usefor await, which does it onbreak. - Connect streams with
pipeline(), notpipe(), so an error closes all of them. - Never rely on garbage collection to close a
FileHandle. - Use
await usingfor anything withSymbol.asyncDispose(file handles, streams, servers, workers) andusingforSymbol.dispose(timers, child processes, readline). - Disposing a stream that hasn't finished aborts it, so
await finished()on the success path. - Implement
[Symbol.asyncDispose]()on your own resource classes, and useAsyncDisposableStackwithmove()for dynamic sets of resources. - Cleanup errors are combined with the original error into a
SuppressedError. - For resources that live as long as the process, see Graceful shutdown.