Haz una copia de una carpeta con BACKUP() y RESTORE(), y ejecuta comandos con SHELL()
BACKUP(filename, directory, [callback], [filter])empaqueta un directorio (con sus subdirectorios) en un solo archivo y se resuelve con{ filename, files, size }. Un archivo existente con ese nombre se sustituye. Sin callback devuelve una promesa.RESTORE(filename, directory, [callback], [filter])desempaqueta un archivo hecho conBACKUP()en un directorio, creando las carpetas necesarias, y se resuelve con{ files, size, path }.SHELL(command, [callback], [cwd])ejecuta un comando de la shell y se resuelve con su salida (stdout). La carpeta es la del proyecto, o el texto que pases como último argumento. Cuando el comando falla, la promesa se rechaza con un error cuyocodees el código de salida. Con callback se llama comocallback(err, stdout, stderr).
SHELL() ejecuta exactamente el texto que le das: nunca construyas el comando a partir de lo que envió un usuario.
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 }));
}