ForgeTotal.js 5
nl

Total.js 5

Maak een back-up van een map met BACKUP() en RESTORE(), en voer opdrachten uit met SHELL()

Total.js 5 · total5@0.0.19 backupshellfiles Uitgevoerd met Total.js 5
  • BACKUP(filename, directory, [callback], [filter]) pakt een map (met submappen) in één bestand en wordt opgelost met { filename, files, size }. Een bestaand bestand met die naam wordt vervangen. Zonder callback geeft het een promise terug.
  • RESTORE(filename, directory, [callback], [filter]) pakt een met BACKUP() gemaakt bestand uit in een map, maakt de benodigde mappen aan en wordt opgelost met { files, size, path }.
  • SHELL(command, [callback], [cwd]) voert een shellopdracht uit en wordt opgelost met de uitvoer (stdout). De map is die van het project, of de tekst die je als laatste argument meegeeft. Als de opdracht mislukt, wordt de promise afgewezen met een fout waarvan de code de exitcode is. Met een callback wordt hij aangeroepen als callback(err, stdout, stderr).

SHELL() voert precies de tekst uit die je geeft: bouw de opdracht nooit op uit wat een gebruiker heeft gestuurd.

controllers/backups.js
const Fs = require('fs');
const Path = require('path');

exports.install = function() {
	ROUTE('GET /backup/', backup);
	ROUTE('GET /shell/', shell);
};

async function backup($) {

	// a folder with a file and a subfolder
	const source = PATH.tmp('source');
	Fs.rmSync(source, { recursive: true, force: true });
	Fs.mkdirSync(Path.join(source, 'sub'), { recursive: true });
	Fs.writeFileSync(Path.join(source, 'a.txt'), 'hello');
	Fs.writeFileSync(Path.join(source, 'sub', 'b.txt'), 'world');

	const file = PATH.tmp('folder.backup');
	const packed = await BACKUP(file, source);

	const target = PATH.tmp('restored');
	Fs.rmSync(target, { recursive: true, force: true });
	const unpacked = await RESTORE(file, target);

	$.json({
		packed: [packed.files, packed.filename === file, Fs.existsSync(file)],
		unpacked: [unpacked.files, unpacked.size, unpacked.path === target],
		content: [Fs.readFileSync(Path.join(target, 'a.txt'), 'utf8'), Fs.readFileSync(Path.join(target, 'sub', 'b.txt'), 'utf8')]
	});
}

async function shell($) {

	const output = await SHELL('echo hello');
	const where = await SHELL('pwd', PATH.tmp());

	let code = null;
	try {
		await SHELL('exit 3');
	} catch (e) {
		code = e.code;
	}

	SHELL('echo from callback', (err, stdout) => $.json({ output: output, where: where.trim() === PATH.tmp() || where.trim().endsWith('/tmp'), code: code, callback: stdout }));
}