Streams and connections
Streams buffer data. An unread or unclosed stream keeps buffers in external memory.
Broken code
Section titled “Broken code”examples/node/05-stream-leak.js — creates readable streams and never destroys them.
Fixed code
Section titled “Fixed code”examples/node/05-stream-fixed.js — stream.destroy(), pipeline() with error handling.
import { pipeline } from 'node:stream/promises';import { createReadStream, createWriteStream } from 'node:fs';
await pipeline( createReadStream('in.dat'), createWriteStream('out.dat'));// auto-cleanup on completion or errorDatabase pools
Section titled “Database pools”// Broken — new pool per requestapp.get('/users', async (req, res) => { const pool = createPool(config); const rows = await pool.query('SELECT ...'); res.json(rows); // pool never closed});Use one shared pool per process; close on SIGTERM.
Run it
Section titled “Run it”node examples/node/05-stream-leak.jsnode examples/node/05-stream-fixed.js