Esegui il backup di una cartella con BACKUP() e RESTORE(), ed esegui comandi con SHELL()
BACKUP(filename, directory, [callback], [filter])impacchetta una directory (con le sue sottodirectory) in un solo file e si risolve con{ filename, files, size }. Un file esistente con quel nome viene sostituito. Senza callback restituisce una promise.RESTORE(filename, directory, [callback], [filter])scompatta un file creato conBACKUP()in una directory, creando le cartelle necessarie, e si risolve con{ files, size, path }.SHELL(command, [callback], [cwd])esegue un comando della shell e si risolve con il suo output (stdout). La cartella è quella del progetto, oppure il testo che passi come ultimo argomento. Quando il comando fallisce, la promise viene rifiutata con un errore il cuicodeè il codice di uscita. Con un callback viene chiamato comecallback(err, stdout, stderr).
SHELL() esegue esattamente il testo che gli dai: non costruire mai il comando a partire da ciò che ha inviato un utente.
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 }));
}