ForgeTotal.js 5
es

Total.js 5

Libera un stream cuando termina con CLEANUP()

Total.js 5 · total5@0.0.19 streamsfilescleanup Ejecutada con Total.js 5

CLEANUP(stream, [callback]) espera a que un stream haya terminado (acabó, se cerró o falló) y entonces lo destruye, lo que libera el manejador de archivo o el socket que hay detrás. Con un callback, este se llama después; sin él devuelve una promesa que se resuelve en ese momento. Es la llamada que conviene hacer después de entregar un stream a algo que lo lee (una respuesta, un pipe, una subida) cuando quieres estar seguro de que nada queda abierto si el otro lado se detiene antes de tiempo.

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 }));
}