Skip to content

Commit 28df75d

Browse files
#11 - javascript
1 parent 7230cb7 commit 28df75d

File tree

1 file changed

+232
-0
lines changed

1 file changed

+232
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
//#11 MANEJO DE FICHEROS
2+
//Bibliography
3+
//Professional JavaScript for web developers by Matt Frisbie [Frisbie, Matt] (z-lib.org)
4+
//GPT
5+
6+
/* The File Type
7+
The File API is still based around the file input field of a form but adds the ability to access the file
8+
information directly. HTML5 adds a files collection to DOM for the file input element. When one
9+
or more files are selected in the field, the files collection contains a sequence of File objects that
10+
represent each file. Each File object has several read-only properties, including:
11+
➤➤ name—The file name on the local system.
12+
➤➤ size—The size of the file in bytes.
13+
Blob and File APIs ❘ 759
14+
➤➤ type—A string containing the MIME type of the file.
15+
➤➤ lastModifiedDate—A string representing the last time the file was modified. This property
16+
has been implemented only in Chrome. */
17+
18+
/* The FileReader Type
19+
The FileReader type represents an asynchronous file-reading mechanism. You can think of File-
20+
Reader as similar to XMLHttpRequest, only it is used for reading files from the file system as opposed
21+
to reading data from the server. The FileReader type offers several methods to read in file data:
22+
➤➤ readAsText(file, encoding)—Reads the file as plain text and stores the text in the
23+
result property. The second argument, the encoding type, is optional.
24+
➤➤ readAsDataURL(file)—Reads the file and stores a data URI representing the files in the
25+
result property.
26+
➤➤ readAsBinaryString(file)—Reads the file and stores a string where each character repre-
27+
sents a byte in the result property.
28+
➤➤ readAsArrayBuffer(file)—Reads the file and stores an ArrayBuffer containing the file
29+
contents in the result property. */
30+
31+
32+
//How ever we will use Node.js to facilitate the files manipulation, so you have to run this file in Node to interact with the console
33+
34+
//short for console.log
35+
let log = console.log;
36+
37+
const fs = require('fs');
38+
const path = require('path');
39+
40+
const githubUser = 'duendeintemporal';
41+
const f_path = path.join(__dirname, `${githubUser}.txt`);
42+
43+
// Data to write in the file
44+
const name = 'Niko Zen';
45+
const age = '41';
46+
const favoriteLanguage = 'JavaScript';
47+
48+
// Create and write to the file
49+
fs.writeFile(f_path, `Name: ${name}\nAge: ${age}\nFavoriteLanguage: ${favoriteLanguage}\n`, (err) => {
50+
if (err) {
51+
console.error('Error creating the file: ', err);
52+
return;
53+
}
54+
log(`File ${githubUser}.txt created successfully.`);
55+
56+
// Read the content of the file
57+
fs.readFile(f_path, 'utf8', (err, data) => {
58+
if (err) {
59+
error(`Error reading the file ${githubUser}.txt: `, err);
60+
return;
61+
}
62+
log('Content of the file: ');
63+
log(data);
64+
65+
// Delete the file
66+
fs.unlink(f_path, (err) => {
67+
if (err) {
68+
error(`Error deleting the file ${githubUser}.txt: `, err);
69+
return;
70+
}
71+
log(`File ${githubUser}.txt deleted successfully.`);
72+
});
73+
});
74+
});
75+
76+
//Extra Dificulty Exercise
77+
78+
const readline = require('readline');
79+
80+
const filePath = 'sales.txt';
81+
82+
const rl = readline.createInterface({
83+
input: process.stdin,
84+
output: process.stdout
85+
});
86+
87+
const menu = () => {
88+
log('\n--- Sales Management ---');
89+
log('1. Add Product');
90+
log('2. View Products');
91+
log('3. Update Product');
92+
log('4. Delete Product');
93+
log('5. Calculate Total Sales');
94+
log('6. Calculate Sales by Product');
95+
log('7. Exit');
96+
rl.question('Select an option: ', handleMenuOption);
97+
};
98+
99+
const handleMenuOption = (option) => {
100+
switch (option) {
101+
case '1':
102+
addProduct();
103+
break;
104+
case '2':
105+
viewProducts();
106+
break;
107+
case '3':
108+
updateProduct();
109+
break;
110+
case '4':
111+
deleteProduct();
112+
break;
113+
case '5':
114+
calculateTotalSales();
115+
break;
116+
case '6':
117+
calculateSalesByProduct();
118+
break;
119+
case '7':
120+
exitProgram();
121+
break;
122+
default:
123+
log('Invalid option, choose a number between 1 and 7. Please try again.');
124+
menu();
125+
break;
126+
}
127+
};
128+
129+
const addProduct = () => {
130+
rl.question('Product Name: ', (name) => {
131+
rl.question('Quantity Sold: ', (quantity) => {
132+
rl.question('Price: ', (price) => {
133+
const product = `${name}, ${quantity}, ${price}\n`;
134+
fs.appendFile(filePath, product, (err) => {
135+
if (err) throw err;
136+
log('Product added.');
137+
menu();
138+
});
139+
});
140+
});
141+
});
142+
};
143+
144+
const viewProducts = () => {
145+
fs.readFile(filePath, 'utf8', (err, data) => {
146+
if (err) throw err;
147+
log('\nProducts:\n' + (data || 'No products registered.'));
148+
menu();
149+
});
150+
};
151+
152+
const updateProduct = () => {
153+
rl.question('Product Name to Update: ', (name) => {
154+
rl.question('New Quantity Sold: ', (newQuantity) => {
155+
rl.question('New Price: ', (newPrice) => {
156+
fs.readFile(filePath, 'utf8', (err, data) => {
157+
if (err) throw err;
158+
const products = data.split('\n').map(line => {
159+
if (line.startsWith(name)) {
160+
return `${name}, ${newQuantity}, ${newPrice}`;
161+
}
162+
return line;
163+
}).join('\n');
164+
fs.writeFile(filePath, products, (err) => {
165+
if (err) throw err;
166+
log('Product updated.');
167+
menu();
168+
});
169+
});
170+
});
171+
});
172+
});
173+
};
174+
175+
const deleteProduct = () => {
176+
rl.question('Product Name to Delete: ', (name) => {
177+
fs.readFile(filePath, 'utf8', (err, data) => {
178+
if (err) throw err;
179+
const products = data.split('\n').filter(line => !line.startsWith(name)).join('\n');
180+
fs.writeFile(filePath, products, (err) => {
181+
if (err) throw err;
182+
log('Product deleted.');
183+
menu();
184+
});
185+
});
186+
});
187+
};
188+
189+
const calculateTotalSales = () => {
190+
fs.readFile(filePath, 'utf8', (err, data) => {
191+
if (err) throw err;
192+
const total = data.split('\n').reduce((sum, line) => {
193+
const parts = line.split(', ');
194+
return sum + (parseInt(parts[1] || 0) * parseFloat(parts[2] || 0));
195+
}, 0);
196+
log(`Total Sales: ${total.toFixed(2)}`);
197+
menu();
198+
});
199+
};
200+
201+
const calculateSalesByProduct = () => {
202+
rl.question('Product Name: ', (name) => {
203+
fs.readFile(filePath, 'utf8', (err, data) => {
204+
if (err) throw err;
205+
const total = data.split('\n').reduce((sum, line) => {
206+
const parts = line.split(', ');
207+
if (parts[0] === name) {
208+
return sum + (parseInt(parts[1] || 0) * parseFloat(parts[2] || 0));
209+
}
210+
return sum;
211+
212+
}, 0);
213+
log(`Total Sales for ${name}: ${total.toFixed(2)}`);
214+
menu();
215+
});
216+
});
217+
};
218+
219+
const exitProgram = () => {
220+
fs.unlink(filePath, (err) => {
221+
if (err) {
222+
error('Error deleting the file:', err);
223+
return;
224+
}
225+
log('Exiting the program and deleting the sales data file.');
226+
rl.close();
227+
});
228+
};
229+
230+
setTimeout(()=>{
231+
menu();
232+
}, 1200);

0 commit comments

Comments
 (0)