Skip to content

Commit b636e8d

Browse files
committed
Add 3-read_file_async.js file
1 parent 7b83228 commit b636e8d

File tree

4 files changed

+72
-59
lines changed

4 files changed

+72
-59
lines changed

0x05-Node_JS_basic/1-stdin.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ process.stdin.on('readable', () => {
55

66
if (name.length > 0) {
77
process.stdout.write(`Your name is: ${name}`);
8-
process.exit();
98
}
109
});
1110

12-
process.stdin.on('exit', () => {
11+
process.stdin.on('end', () => {
1312
process.stdout.write('This important software is now closing\n');
1413
});

0x05-Node_JS_basic/2-read_file.js

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,43 +7,42 @@ const fs = require('fs');
77
*/
88

99
function countStudents(path) {
10-
try {
11-
const data = fs.readFileSync(path, 'utf8').split('\n');
10+
if (!fs.existsSync(path)) {
11+
throw new Error('Cannot load the database');
12+
}
13+
const data = fs.readFileSync(path, 'utf8').split('\n');
1214

13-
if (data.length === 0) {
14-
throw new Error('Cannot load the database');
15-
}
16-
const students = data.map((line) => line.split(','));
15+
if (data.length === 0) {
16+
throw new Error('Cannot load the database');
17+
}
18+
const students = data.map((line) => line.split(','));
1719

18-
console.log(`Number of students: ${students.slice(1).length - 1}`);
20+
console.log(`Number of students: ${students.slice(1).length - 1}`);
1921

20-
const fields = students[0];
21-
const fieldIndex = fields.indexOf('field');
22+
const fields = students[0];
23+
const fieldIndex = fields.indexOf('field');
2224

23-
if (fieldIndex === -1) {
24-
throw new Error('Field column not found');
25-
}
25+
if (fieldIndex === -1) {
26+
throw new Error('Field column not found');
27+
}
28+
29+
const validStudents = students
30+
.slice(1)
31+
.filter((student) => student[fieldIndex] !== undefined && student[fieldIndex] !== '');
2632

27-
const validStudents = students
28-
.slice(1)
29-
.filter((student) => student[fieldIndex] !== undefined && student[fieldIndex] !== '');
30-
31-
const classes = validStudents.reduce((acc, student) => {
32-
const className = student[fieldIndex];
33-
if (!acc[className]) {
34-
acc[className] = [];
35-
}
36-
acc[className].push(student[fields.indexOf('firstname')]);
37-
return acc;
38-
}, {});
39-
40-
for (const [className, studentList] of Object.entries(classes)) {
41-
console.log(`Number of students in ${className}: ${studentList.length}. List: ${studentList.join(', ')}`);
33+
const classes = validStudents.reduce((acc, student) => {
34+
const className = student[fieldIndex];
35+
if (!acc[className]) {
36+
acc[className] = [];
4237
}
43-
} catch (error) {
44-
console.error(error.message);
38+
acc[className].push(student[fields.indexOf('firstname')]);
39+
return acc;
40+
}, {});
41+
42+
for (const [className, studentList] of Object.entries(classes)) {
43+
console.log(`Number of students in ${className}: ${studentList.length}. List: ${studentList.join(', ')}`);
4544
}
4645
}
4746

48-
countStudents('database.csv');
47+
// countStudents('database.csv');
4948
module.exports = countStudents;

0x05-Node_JS_basic/3-read_file_async.js

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,39 @@ const fs = require('fs/promises');
55
* @param {String} path - The path to the CSV data file.
66
* @returns {Promise<void>}
77
*/
8-
const countStudents = async (path) => {
9-
try {
10-
const data = await fs.readFile(path, 'utf-8');
11-
const fileLines = data.trim().split('\n');
12-
const studentGroups = {};
13-
const dbFieldNames = fileLines[0].split(',');
14-
const studentPropNames = dbFieldNames.slice(0, -1);
158

16-
fileLines.slice(1).forEach((line) => {
17-
const [field, ...studentPropValues] = line.split(',');
18-
studentGroups[field] = [
19-
...(studentGroups[field] || []),
20-
Object.fromEntries(studentPropNames.map((propName, idx) => [propName, studentPropValues[idx]])),
21-
];
22-
});
23-
24-
const totalStudents = Object.values(studentGroups).flat().length;
25-
console.log(`Number of students: ${totalStudents}`);
9+
const countStudents = (path) =>
10+
new Promise((resolve, reject) => {
11+
fs.readFile(path, 'utf-8', (err, data) => {
12+
if (err) {
13+
reject(new Error('Cannot load the database'));
14+
}
15+
if (data) {
16+
const fileLines = data.toString('utf-8').trim().split('\n');
17+
const studentObj = {};
18+
const fieldNames = fileLines[0].split(',');
19+
const studentPropNames = fieldNames.slice(0, fieldNames.length - 1);
2620

27-
for (const [field, group] of Object.entries(studentGroups)) {
28-
const studentNames = group.map((student) => student.firstname).join(', ');
29-
console.log(`Number of students in ${field}: ${group.length}. List: ${studentNames}`);
30-
}
21+
for (const line of fileLines.slice(1)) {
22+
const studentRow = line.split(',');
23+
const studentPropValues = studentRow.slice(0, studentRow.length - 1);
24+
const field = studentRow[studentRow.length - 1];
25+
if (!Object.keys(studentObj).includes(field)) {
26+
studentObj[field] = [];
27+
}
28+
const studentEntries = studentPropNames.map((propName, idx) => [propName, studentPropValues[idx]]);
29+
studentObj[field].push(Object.fromEntries(studentEntries));
30+
}
3131

32-
return true;
33-
} catch (error) {
34-
console.error('Cannot load the database');
35-
throw error;
36-
}
37-
};
32+
const totalStudents = Object.values(studentObj).reduce((pre, cur) => (pre || []).length + cur.length);
33+
console.log(`Number of students: ${totalStudents}`);
34+
for (const [field, group] of Object.entries(studentObj)) {
35+
const studentNames = group.map((student) => student.firstname).join(', ');
36+
console.log(`Number of students in ${field}: ${group.length}. List: ${studentNames}`);
37+
}
38+
resolve(true);
39+
}
40+
});
41+
});
3842

3943
module.exports = countStudents;

0x05-Node_JS_basic/main.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const countStudents = require('./2-read_file.js');
2+
3+
countStudents('nope.csv');
4+
// .then(() => {
5+
// console.log('Done!');
6+
// })
7+
// .catch((error) => {
8+
// console.log(error);
9+
// });
10+
11+
//countStudents('database.csv');

0 commit comments

Comments
 (0)