ForgeTotal.js 5
de

Total.js 5

Einen Ordner mit BACKUP() und RESTORE() sichern und Befehle mit SHELL() ausführen

Total.js 5 · total5@0.0.19 backupshellfiles Mit Total.js 5 ausgeführt
  • BACKUP(filename, directory, [callback], [filter]) packt ein Verzeichnis (mit seinen Unterverzeichnissen) in eine Datei und wird mit { filename, files, size } aufgelöst. Eine vorhandene Datei mit diesem Namen wird ersetzt. Ohne Callback gibt es ein Promise zurück.
  • RESTORE(filename, directory, [callback], [filter]) entpackt eine mit BACKUP() erstellte Datei in ein Verzeichnis, legt die nötigen Ordner an und wird mit { files, size, path } aufgelöst.
  • SHELL(command, [callback], [cwd]) führt einen Shell-Befehl aus und wird mit seiner Ausgabe (stdout) aufgelöst. Der Ordner ist der des Projekts oder der Text, den du als letztes Argument übergibst. Schlägt der Befehl fehl, wird das Promise mit einem Fehler abgelehnt, dessen code der Exit-Code ist. Mit einem Callback wird er als callback(err, stdout, stderr) aufgerufen.

SHELL() führt genau den Text aus, den du ihm gibst: Baue den Befehl nie aus dem, was ein Benutzer gesendet hat.

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