Repository navigation
Expand file tree
/
Copy path3-read_file_async.js
More file actions
45 lines (40 loc) · 1.54 KB
/
Copy path3-read_file_async.js
File metadata and controls
45 lines (40 loc) · 1.54 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
const fs = require('fs');
const countStudents = (dataPath) => new Promise((resolve, reject) => {
fs.readFile(dataPath, 'utf-8', (err, data) => {
if (err) {
reject(new Error('Cannot load the database'));
}
if (data) {
const fileLines = data
.toString('utf-8')
.trim()
.split('\n');
const studentGroups = {};
const dbFieldNames = fileLines[0].split(',');
const studentPropNames = dbFieldNames
.slice(0, dbFieldNames.length - 1);
for (const line of fileLines.slice(1)) {
const studentRecord = line.split(',');
const studentPropValues = studentRecord
.slice(0, studentRecord.length - 1);
const field = studentRecord[studentRecord.length - 1];
if (!Object.keys(studentGroups).includes(field)) {
studentGroups[field] = [];
}
const studentEntries = studentPropNames
.map((propName, idx) => [propName, studentPropValues[idx]]);
studentGroups[field].push(Object.fromEntries(studentEntries));
}
const totalStudents = Object
.values(studentGroups)
.reduce((pre, cur) => (pre || []).length + cur.length);
console.log(`Number of students: ${totalStudents}`);
for (const [field, group] of Object.entries(studentGroups)) {
const studentNames = group.map((student) => student.firstname).join(', ');
console.log(`Number of students in ${field}: ${group.length}. List: ${studentNames}`);
}
resolve(true);
}
});
});
module.exports = countStudents;