Release a stream when it ends with CLEANUP()
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.
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 }));
}