Created
April 23, 2017 18:35
-
-
Save UlisesGascon/d13c40a7052c2a4f9f39bfc2c1377b36 to your computer and use it in GitHub Desktop.
Ejemplo de eventos para "Pensar Asícronamente en un mundo síncrono"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require("fs"); | |
var events = require('events'); | |
var ee = events.EventEmitter; | |
var emisorEventos = new ee(); | |
function leerArchivo(nombre) { | |
console.log("Empezando la lectura de ", nombre); | |
fs.readFile(nombre, "utf-8", function(error, contenido) { | |
if (error) { | |
console.log("Error en la lectura"); | |
return emisorEventos.emit('fichero:error', error); | |
} | |
console.log("Lectura finalizada en ", nombre); | |
emisorEventos.emit('fichero:leido', { | |
"nombre": nombre, | |
"longitud": contenido.length | |
}); | |
}); | |
} | |
var ficherosLeidos = 0; | |
emisorEventos.on('fichero:leido', function(fichero) { | |
console.log(fichero.nombre + " tiene " + fichero.longitud + " caracteres"); | |
ficherosLeidos++; | |
if (ficherosLeidos === 3) { | |
emisorEventos.emit('fichero:terminado'); | |
} | |
}); | |
emisorEventos.on('fichero:terminado', function() { | |
console.log("¿Tenemos todas las respuestas?", ficherosLeidos === 3); | |
}); | |
emisorEventos.on('fichero:error', function(err) { | |
console.log("No tuvimos éxito!"); | |
console.log("Err:", err); | |
}); | |
leerArchivo("./fichero-1.txt"); | |
leerArchivo("./fichero-2.txt"); | |
leerArchivo("./fichero-3.txt"); | |
/* ---- Console output ---- | |
Empezando la lectura de ./fichero-1.txt | |
Empezando la lectura de ./fichero-2.txt | |
Empezando la lectura de ./fichero-3.txt | |
Lectura finalizada en ./fichero-3.txt | |
./fichero-3.txt tiene 15 caracteres | |
Lectura finalizada en ./fichero-1.txt | |
./fichero-1.txt tiene 8 caracteres | |
Lectura finalizada en ./fichero-2.txt | |
./fichero-2.txt tiene 111 caracteres | |
¿Tenemos todas las respuestas? true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment