ForgeTotal.js 5
nl

Total.js 5

Geef een stream vrij als hij eindigt met CLEANUP()

Total.js 5 · total5@0.0.19 streamsfilescleanup Uitgevoerd met Total.js 5

CLEANUP(stream, [callback]) wacht tot een stream klaar is (hij is afgelopen, gesloten of mislukt) en vernietigt hem dan, waardoor de bestandshandle of de socket erachter wordt vrijgegeven. Met een callback wordt die daarna aangeroepen; zonder callback geeft de functie een promise terug die op dat moment wordt opgelost. Het is de aanroep die je doet nadat je een stream hebt overgedragen aan iets dat hem leest (een antwoord, een pipe, een upload) als je zeker wilt zijn dat niets open blijft als de andere kant eerder stopt.

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