ForgeTotal.js 5
pt

Total.js 5

Liberte um stream quando termina com CLEANUP()

Total.js 5 · total5@0.0.19 streamsfilescleanup Executada com o Total.js 5

CLEANUP(stream, [callback]) espera que um stream tenha terminado (acabou, foi fechado ou falhou) e depois destrói-o, o que liberta o descritor de ficheiro ou o socket que está por trás. Com um callback, este é chamado depois; sem ele devolve uma promessa que se resolve nesse momento. É a chamada a fazer depois de entregar um stream a algo que o lê (uma resposta, um pipe, um upload) quando quer ter a certeza de que nada fica aberto se o outro lado parar mais cedo.

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