-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05.js
More file actions
82 lines (62 loc) · 1.93 KB
/
05.js
File metadata and controls
82 lines (62 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import fs from "fs";
try {
let usuario = undefined;
console.log(usuario.nombre); // error porque usuario es undefined
} catch (error) {
console.log("No se pudo leer la propiedad");
}
// El problema con try/catch y asincronía
// ❌ try/catch NO funciona con callbacks asíncronos
try {
setTimeout(() => {
throw new Error("Algo salió mal"); // Este error NO lo atrapa el try/catch
}, 1000);
} catch (error) {
console.log("Nunca llega aquí"); // Nunca se ejecuta
}
// El try/catch ya terminó cuando el callback se ejecuta.
// El error queda sin manejar y puede crashear el proceso.
// la convención de callbacks con error-first
fs.readFile("archivo.txt", "utf8", (err, data) => {
if (err) {
console.error("Error leyendo el archivo:", err.message);
return;
}
console.log("Contenido:", data);
});
// Estructura de error-first
function callback(error, resultado) {}
// Error-first en APIs de Node.js
const fs = require("fs");
// fs.readFile sigue exactamente la convención error-first
fs.readFile("archivo.txt", "utf8", function(error, datos) {
if (error) {
console.error("No se pudo leer el archivo:", error.message);
return;
}
console.log("Contenido:", datos);
});
// Lo mismo con fs.writeFile
fs.writeFile("salida.txt", "Hola mundo", function(error) {
if (error) {
console.error("Error al escribir:", error.message);
return;
}
console.log("Archivo guardado correctamente");
});
// ❌ Sin return — código peligroso
function procesarDatos(error, datos) {
if (error) {
console.error("Error:", error.message);
// ¡Falta el return! La función sigue ejecutándose
}
console.log(datos.length); // 💥 TypeError si datos es null
}
// ✅ Con return — código seguro
function procesarDatos(error, datos) {
if (error) {
console.error("Error:", error.message);
return; // Corta la ejecución aquí
}
console.log(datos.length); // Solo llega aquí si no hubo error
}