1. Frontend + Backend para Crear Carpetas y Archivos
-
Utiliza JavaScript/HTML/CSS para crear una interfaz donde el usuario pueda
agregar un árbol (
tree
) de directorios y archivos. -
Implementa un backend en en Node.js para manejar las operaciones del sistema
de archivos utilizando el módulo
fs
. - En el frontend, podrías enviar la estructura del árbol como un objeto JSON al servidor, el cual crearía las carpetas y archivos en la ubicación correspondiente.
2. Edición y Visualización del Contenido
- Puedes implementar una interfaz de administración (ventana de edición) y otra de invitados (solo visualización) usando JavaScript y AJAX para cargar datos dinámicamente desde el backend.
- En el backend, podrías almacenar y servir estos datos en archivos JSON o bases de datos.
A continuación, te dejo un ejemplo simplificado que combina frontend y backend
para simular parte de la funcionalidad:
Backend (Node.js)
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
app.use(express.json());
const htdocsPath = path.join(process.env.HOME || process.env.USERPROFILE, "Desktop", "htdocs");
// Crear carpeta `htdocs` si no existe
if (!fs.existsSync(htdocsPath)) {
fs.mkdirSync(htdocsPath);
}
// Endpoint para crear archivos y carpetas desde un árbol JSON
app.post("/create-tree", (req, res) => {
const tree = req.body;
const createStructure = (basePath, tree) => {
for (const item of tree) {
if (item.type === "folder") {
const folderPath = path.join(basePath, item.name);
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
if (item.children) {
createStructure(folderPath, item.children);
}
} else if (item.type === "file") {
const filePath = path.join(basePath, item.name);
fs.writeFileSync(filePath, item.content || "");
}
}
};
createStructure(htdocsPath, tree);
res.send("Estructura creada exitosamente");
});
// Endpoint para recuperar archivos en formato JSON
app.get("/get-tree", (req, res) => {
const getStructure = (dir) => {
return fs.readdirSync(dir).map((file) => {
const fullPath = path.join(dir, file);
const isDirectory = fs.lstatSync(fullPath).isDirectory();
if (isDirectory) {
return { name: file, type: "folder", children: getStructure(fullPath) };
} else {
return { name: file, type: "file", content: fs.readFileSync(fullPath, "utf-8") };
}
});
};
res.json(getStructure(htdocsPath));
});
app.listen(3000, () => console.log("Servidor escuchando en el puerto 3000"));
Frontend (HTML + JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Administrador de Archivos</title>
</head>
<body>
<h1>Gestión de Archivos y Carpetas</h1>
<button id="create-tree">Crear Árbol</button>
<button id="get-tree">Obtener Datos</button>
<div id="output"></div>
<script>
// Ejemplo de árbol
const tree = [
{ type: "folder", name: "Carpeta1", children: [
{ type: "file", name: "archivo1.txt", content: "Contenido de archivo1" },
{ type: "folder", name: "SubCarpeta1", children: [
{ type: "file", name: "archivo2.txt", content: "Contenido de archivo2" }
]}
]},
{ type: "file", name: "archivo3.txt", content: "Contenido de archivo3" }
];
document.getElementById("create-tree").onclick = () => {
fetch("http://localhost:3000/create-tree", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(tree)
}).then(response => response.text())
.then(data => alert(data));
};
document.getElementById("get-tree").onclick = () => {
fetch("http://localhost:3000/get-tree")
.then(response => response.json())
.then(data => {
document.getElementById("output").textContent = JSON.stringify(data, null, 2);
});
};
</script>
</body>
</html>
Explicación:
1. Backend: Node.js maneja las operaciones del sistema de archivos y define los endpoints necesarios para crear y recuperar datos.2. Frontend: Proporciona botones para crear la estructura (enviada como JSON) y para recuperar la estructura existente.
Este es un ejemplo práctico y funcional para la creación y manipulación de archivos.