Skip to content

Commit 315e639

Browse files
authored
Merge pull request mouredev#7500 from Kenysdev/11_15.js
#11 - javascript -> #15
2 parents 5e2df21 + 934e9f5 commit 315e639

File tree

5 files changed

+610
-0
lines changed

5 files changed

+610
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
/*
2+
_____________________________________
3+
https://github.com/kenysdev
4+
2024 - JavaScript
5+
_______________________________________
6+
#11 MANEJO DE FICHEROS
7+
---------------------------------------
8+
 * IMPORTANTE: Sólo debes subir el fichero de código como parte del ejercicio.
9+
 *
10+
 * EJERCICIO:
11+
 * Desarrolla un programa capaz de crear un archivo que se llame como
12+
 * tu usuario de GitHub y tenga la extensión .txt.
13+
 * Añade varias líneas en ese fichero:
14+
 * - Tu nombre.
15+
 * - Edad.
16+
 * - Lenguaje de programación favorito.
17+
 * Imprime el contenido.
18+
 * Borra el fichero.
19+
 *
20+
 * DIFICULTAD EXTRA (opcional):
21+
 * Desarrolla un programa de gestión de ventas que almacena sus datos en un
22+
 * archivo .txt.
23+
 * - Cada producto se guarda en una línea del arhivo de la siguiente manera:
24+
 *   [nombre_producto], [cantidad_vendida], [precio].
25+
 * - Siguiendo ese formato, y mediante terminal, debe permitir añadir, consultar,
26+
 *   actualizar, eliminar productos y salir.
27+
 * - También debe poseer opciones para calcular la venta total y por producto.
28+
 * - La opción salir borra el .txt.
29+
*/
30+
31+
// ________________________________________________________
32+
const fs = require("fs/promises");
33+
const path = require("path");
34+
35+
class File {
36+
constructor(filePath) {
37+
this._path = filePath;
38+
}
39+
40+
async writeLine(line) {
41+
try {
42+
await fs.appendFile(this._path, line + "\n");
43+
} catch (error) {
44+
console.error("Error -> writeLine ->", error.message);
45+
}
46+
}
47+
48+
async writeLines(lines) {
49+
try {
50+
await fs.writeFile(this._path, lines.join("\n"));
51+
} catch (error) {
52+
console.error("Error -> writeLines ->", error.message);
53+
}
54+
}
55+
56+
async readLine() {
57+
try {
58+
const data = await fs.readFile(this._path, "utf-8");
59+
const lines = data.split("\n").filter(Boolean);
60+
return lines[lines.length - 1] || null;
61+
} catch (error) {
62+
console.error("Error -> readLine ->", error.message);
63+
return null;
64+
}
65+
}
66+
67+
async readLines() {
68+
try {
69+
const data = await fs.readFile(this._path, "utf-8");
70+
return [...data.split("\n").filter(Boolean)];
71+
} catch (error) {
72+
console.error("Error -> readLines ->", error.message);
73+
return [];
74+
}
75+
}
76+
77+
async deleteFile() {
78+
try {
79+
await fs.unlink(this._path);
80+
console.log(`${this._path} -> eliminado.`);
81+
} catch (error) {
82+
console.error("Error -> deleteFile ->", error.message);
83+
}
84+
}
85+
86+
async printAll() {
87+
try {
88+
const data = await fs.readFile(this._path, "utf-8");
89+
console.log(data);
90+
} catch (error) {
91+
console.error("Error -> printAll ->", error.message);
92+
}
93+
}
94+
95+
async queryFile(query) {
96+
try {
97+
const lines = await this.readLines();
98+
for (let i = 0; i < lines.length; i++) {
99+
const line = lines[i];
100+
const productName = line.split(",")[0].trim();
101+
if (productName === `[${query}]`) {
102+
console.log(line);
103+
return i;
104+
}
105+
}
106+
console.log("No existe.");
107+
return null;
108+
} catch (error) {
109+
console.error("Error -> queryFile ->", error.message);
110+
return null;
111+
}
112+
}
113+
}
114+
115+
// __________________________
116+
async function ejmp() {
117+
const user = new File(path.resolve("kenysdev.txt"));
118+
await user.writeLine("Name: ken");
119+
await user.writeLine("Age: 121");
120+
await user.writeLine("PL: JS");
121+
await user.printAll();
122+
const name = await user.readLine()
123+
console.log(name);
124+
await user.deleteFile();
125+
}
126+
127+
// ________________________________________________________
128+
// DIFICULTAD EXTRA
129+
130+
const sale = new File(path.resolve("sale_mgt.txt"));
131+
132+
async function addProduct(product = null, qty = null, price = null) {
133+
while (true) {
134+
if (!product || !/^[a-zA-Z]+$/.test(product)) {
135+
console.log("Debe ingresar un nombre de producto válido.");
136+
product = await Input("Producto: ");
137+
} else if (!qty || !/^[0-9]+$/.test(qty)) {
138+
console.log("Debe ingresar una cantidad válida.");
139+
qty = await Input("Cantidad: ");
140+
} else if (!price || isNaN(parseFloat(price))) {
141+
console.log("Debe ingresar un precio válido.");
142+
price = await Input("Precio: ");
143+
} else {
144+
const line = `[${product}], [${qty}], [${price}]`;
145+
await sale.writeLine(line);
146+
console.log("\nGuardado.");
147+
return;
148+
}
149+
}
150+
}
151+
152+
async function queryProduct(query = "") {
153+
if (!query) {
154+
query = await Input("\nConsultar Producto.\nNombre: ");
155+
}
156+
await sale.queryFile(query);
157+
}
158+
159+
async function deleteProduct(query = "") {
160+
if (!query) {
161+
query = await Input("\nEliminar Producto.\nNombre: ");
162+
}
163+
const lineIndex = await sale.queryFile(query);
164+
if (lineIndex !== null) {
165+
const lines = await sale.readLines();
166+
lines.splice(lineIndex, 1);
167+
lines.push('')
168+
await sale.writeLines(lines);
169+
console.log("Producto eliminado");
170+
}
171+
}
172+
173+
async function updateProduct(query = "") {
174+
if (!query) {
175+
query = await Input("\nEditar Producto.\nNombre: ");
176+
}
177+
const lineIndex = await sale.queryFile(query);
178+
if (lineIndex !== null) {
179+
const lines = await sale.readLines();
180+
console.log("Ingrese los nuevos datos del producto:");
181+
await addProduct();
182+
lines[lineIndex] = await sale.readLine();
183+
lines.push('')
184+
await sale.writeLines(lines);
185+
}
186+
}
187+
188+
async function invoice() {
189+
console.log("\nFactura\n-------------------------");
190+
const lines = await sale.readLines();
191+
let totalAmount = 0;
192+
193+
for (const line of lines) {
194+
const [product, qty, price] = line.split(",").map(item => item.trim().replace(/\[|\]/g, ""));
195+
const subTotal = parseInt(qty) * parseFloat(price);
196+
console.log(`${line} -> $${subTotal.toFixed(2)}`);
197+
totalAmount += subTotal;
198+
}
199+
200+
console.log("\nMonto Total -> $" + totalAmount.toFixed(2));
201+
}
202+
203+
// __________________________
204+
const menu = (`
205+
Gestión de Ventas:
206+
╔═════════════════════════════════╗
207+
║ 1. Agregar 4. Editar ║
208+
║ 2. Consultar 5. Facturar ║
209+
║ 3. Eliminar 6. Salir ║
210+
╚═════════════════════════════════╝
211+
`);
212+
213+
const readline = require("readline");
214+
const rl = readline.createInterface({
215+
input: process.stdin,
216+
output: process.stdout
217+
});
218+
219+
function Input(query) {
220+
return new Promise(resolve => rl.question(query, resolve));
221+
}
222+
223+
(async () => {
224+
await ejmp();
225+
while (true) {
226+
console.log(menu)
227+
const option = await Input("\nOpción: ");
228+
switch (option) {
229+
case "1":
230+
await addProduct();
231+
break;
232+
case "2":
233+
await queryProduct();
234+
break;
235+
case "3":
236+
await deleteProduct();
237+
break;
238+
case "4":
239+
await updateProduct();
240+
break;
241+
case "5":
242+
await invoice();
243+
break;
244+
case "6":
245+
console.log("Adiós");
246+
await sale.deleteFile();
247+
rl.close();
248+
return;
249+
default:
250+
console.log("Seleccione una opción entre 1 y 6.");
251+
}
252+
}
253+
})();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
_____________________________________
3+
https://github.com/kenysdev
4+
2024 - JavaScript
5+
_______________________________________
6+
#12 JSON Y XML
7+
---------------------------------------
8+
 * IMPORTANTE: Sólo debes subir el fichero de código como parte del ejercicio.
9+
 *
10+
 * EJERCICIO:
11+
 * Desarrolla un programa capaz de crear un archivo XML y JSON que guarde los
12+
 * siguientes datos (haciendo uso de la sintaxis correcta en cada caso):
13+
 * - Nombre
14+
 * - Edad
15+
 * - Fecha de nacimiento
16+
 * - Listado de lenguajes de programación
17+
 * Muestra el contenido de los archivos.
18+
 * Borra los archivos.
19+
 *
20+
 * DIFICULTAD EXTRA (opcional):
21+
 * Utilizando la lógica de creación de los archivos anteriores, crea un
22+
 * programa capaz de leer y transformar en una misma clase custom de tu
23+
 * lenguaje los datos almacenados en el XML y el JSON.
24+
 * Borra los archivos.
25+
*/
26+
27+
// ________________________________________________________
28+
import { writeFile, readFile, unlink } from "fs/promises";
29+
import { extname } from "path";
30+
import { parseStringPromise, Builder } from "xml2js";
31+
32+
// Datos iniciales
33+
const dictUser = {
34+
name: "Ken",
35+
age: 121,
36+
dob: "1903-03-19",
37+
prog_langs: ["cs", "py", "vb", "rs", "js"],
38+
};
39+
40+
(async () => {
41+
try {``
42+
//____________________________________
43+
// * JSON
44+
45+
// Serialización: Convertir objeto a JSON
46+
const jsonUser = JSON.stringify(dictUser, null, 4);
47+
48+
// Crear archivo JSON
49+
await writeFile("user.json", jsonUser, "utf8");
50+
console.log("Archivo JSON creado.");
51+
52+
// Deserialización: Leer y convertir JSON a objeto
53+
const jsonData = await readFile("user.json", "utf8");
54+
const parsedJson = JSON.parse(jsonData);
55+
console.log("Objeto cargado desde JSON:", parsedJson);
56+
57+
//____________________________________
58+
// * XML
59+
60+
// Serialización: Crear XML a partir de objeto
61+
const builder = new Builder();
62+
const xmlUser = builder.buildObject({ user: dictUser });
63+
64+
// Crear archivo XML
65+
await writeFile("user.xml", xmlUser, "utf8");
66+
console.log("Archivo XML creado.");
67+
68+
// Deserialización: Leer y convertir XML a objeto
69+
const xmlData = await readFile("user.xml", "utf8");
70+
const parsedXml = await parseStringPromise(xmlData);
71+
console.log("Objeto cargado desde XML:", parsedXml.user);
72+
73+
//____________________________________
74+
// DIFICULTAD EXTRA
75+
76+
class XmlOrJson {
77+
constructor(filePath) {
78+
this.filePath = filePath;
79+
this.extension = extname(filePath).toLowerCase();
80+
this.data = {};
81+
}
82+
83+
async asDict() {
84+
try {
85+
if (this.extension === ".json") {
86+
const jsonContent = await readFile(this.filePath, "utf8");
87+
this.data = JSON.parse(jsonContent);
88+
console.log("Archivo JSON cargado correctamente.");
89+
} else if (this.extension === ".xml") {
90+
const xmlContent = await readFile(this.filePath, "utf8");
91+
const parsedXml = await parseStringPromise(xmlContent);
92+
this.data = parsedXml.user;
93+
console.log("Archivo XML cargado correctamente.");
94+
} else {
95+
throw new Error("Extensión de archivo no soportada.");
96+
}
97+
return this.data;
98+
} catch (error) {
99+
console.error("Error al cargar archivo:", error.message);
100+
}
101+
}
102+
}
103+
104+
//____________________________________
105+
console.log("\nDIFICULTAD EXTRA\n");
106+
107+
// Leer JSON
108+
const jsonFile = new XmlOrJson("user.json");
109+
const jsonDict = await jsonFile.asDict();
110+
console.log("Datos desde JSON:", jsonDict);
111+
112+
// Leer XML
113+
const xmlFile = new XmlOrJson("user.xml");
114+
const xmlDict = await xmlFile.asDict();
115+
console.log("Datos desde XML:", xmlDict);
116+
117+
// Eliminar archivos
118+
await unlink("user.json");
119+
await unlink("user.xml");
120+
console.log("Archivos eliminados.");
121+
} catch (error) {
122+
console.error("Error general:", error.message);
123+
}
124+
})();

0 commit comments

Comments
 (0)