# Release a stream when it ends with CLEANUP()

> Use CLEANUP() to destroy a stream as soon as it has finished or failed, so that file handles are not left open, with a callback or as a promise.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: dcaf443c6e5b758eb7c3a4ea92ba9c0289551a3b46dcb0c1e3d642c51e142f37
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`CLEANUP(stream, [callback])` waits until a stream has **finished** (it ended, it was closed or it failed) and then destroys it, which frees the file handle or the socket behind it. With a callback it is called after that; without one it returns a promise that resolves at that moment. It is the call to make after you hand a stream to something that reads it (a response, a pipe, an upload) when you want to be sure that nothing stays open if the other side stops early.

```js controllers/streams.js
const Fs = require('fs');
const { PassThrough } = require('stream');

exports.install = function() {
	ROUTE('GET /copy/', copy);
	ROUTE('GET /copy-callback/', copycallback);
};

async function copy($) {

	const file = PATH.tmp('cleanup.txt');
	Fs.writeFileSync(file, 'some text to read');

	const stream = Fs.createReadStream(file);
	const chunks = [];

	// a sink that reads everything
	const sink = new PassThrough();
	sink.on('data', chunk => chunks.push(chunk));
	stream.pipe(sink);

	const before = stream.destroyed;
	await CLEANUP(stream);

	$.json({ before: before, after: stream.destroyed, content: Buffer.concat(chunks).toString() });
}

function copycallback($) {

	const file = PATH.tmp('cleanup.txt');
	Fs.writeFileSync(file, 'again');

	const stream = Fs.createReadStream(file);
	stream.resume();

	CLEANUP(stream, () => $.json({ destroyed: stream.destroyed }));
}
```
