|
| 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 | +})(); |
0 commit comments