Skip to content

Commit ba9048f

Browse files
committed
#12 - JavaScript
1 parent 216c166 commit ba9048f

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
const fs = require('fs');
2+
const xml2js = require('xml2js');
3+
4+
const datos = {
5+
nombre: 'Eduardo Molina',
6+
edad: 25,
7+
fechaNacimiento: '30-08-1999',
8+
lenguajes: ['JavaScript', 'Python', 'Java']
9+
};
10+
11+
const crearJSON = () => {
12+
fs.writeFileSync('datos.json', JSON.stringify(datos, null, 2), 'utf-8');
13+
console.log('Archivo JSON creado:\n', fs.readFileSync('datos.json', 'utf-8'));
14+
};
15+
16+
const crearXML = () => {
17+
const builder = new xml2js.Builder({ headless: true, rootName: 'persona' });
18+
const xml = builder.buildObject({
19+
nombre: datos.nombre,
20+
edad: datos.edad,
21+
fechaNacimiento: datos.fechaNacimiento,
22+
lenguajes: { lenguaje: datos.lenguajes }
23+
});
24+
fs.writeFileSync('datos.xml', xml, 'utf-8');
25+
console.log('Archivo XML creado:\n', fs.readFileSync('datos.xml', 'utf-8'));
26+
};
27+
28+
29+
class Persona {
30+
31+
constructor(nombre, edad, fechaNacimiento, lenguajes) {
32+
this.nombre = nombre;
33+
this.edad = edad;
34+
this.fechaNacimiento = fechaNacimiento;
35+
this.lenguajes = lenguajes;
36+
}
37+
38+
mostrarDatos() {
39+
console.log(`Nombre: ${this.nombre}`);
40+
console.log(`Edad: ${this.edad}`);
41+
console.log(`Fecha de Nacimiento: ${this.fechaNacimiento}`);
42+
console.log(`Lenguajes: ${this.lenguajes.join(', ')}`);
43+
}
44+
}
45+
46+
const leerYTransformarJSON = () => {
47+
const dataJSON = fs.readFileSync('datos.json', 'utf-8');
48+
const datosJSON = JSON.parse(dataJSON);
49+
const personaJSON = new Persona(
50+
datosJSON.nombre,
51+
datosJSON.edad,
52+
datosJSON.fechaNacimiento,
53+
datosJSON.lenguajes
54+
);
55+
console.log('\nDatos leídos del archivo JSON:');
56+
personaJSON.mostrarDatos();
57+
};
58+
59+
const leerYTransformarXML = () => {
60+
const dataXML = fs.readFileSync('datos.xml', 'utf-8');
61+
xml2js.parseString(dataXML, (err, result) => {
62+
if (err) throw err;
63+
const datosXML = result.persona;
64+
const personaXML = new Persona(
65+
datosXML.nombre[0],
66+
datosXML.edad[0],
67+
datosXML.fechaNacimiento[0],
68+
datosXML.lenguajes[0].lenguaje
69+
);
70+
console.log('\nDatos leídos del archivo XML:');
71+
personaXML.mostrarDatos();
72+
});
73+
};
74+
75+
const borrarArchivos = () => {
76+
fs.unlinkSync('datos.json');
77+
fs.unlinkSync('datos.xml');
78+
console.log('\nArchivos borrados.');
79+
};
80+
81+
crearJSON();
82+
crearXML();
83+
leerYTransformarJSON();
84+
leerYTransformarXML();
85+
borrarArchivos();

0 commit comments

Comments
 (0)