-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-read_file_async.js
executable file
·43 lines (41 loc) · 1.32 KB
/
3-read_file_async.js
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
// Function that reads from a file asynchronously
const { readFile } = require('fs');
function countStudents(fileName) {
const students = {};
const fields = {};
let length = 0;
return new Promise((resolve, reject) => {
readFile(fileName, (error, data) => {
if (error) {
reject(Error('Cannot load the database'));
} else {
const lines = data.toString().split('\n');
for (let i = 0; i < lines.length; i += 1) {
if (lines[i]) {
length += 1;
const field = lines[i].toString().split(',');
if (Object.prototype.hasOwnProperty.call(students, field[3])) {
students[field[3]].push(field[0]);
} else {
students[field[3]] = [field[0]];
}
if (Object.prototype.hasOwnProperty.call(fields, field[3])) {
fields[field[3]] += 1;
} else {
fields[field[3]] = 1;
}
}
}
const l = length - 1;
console.log(`Number of students: ${l}`);
for (const [key, value] of Object.entries(fields)) {
if (key !== 'field') {
console.log(`Number of students in ${key}: ${value}. List: ${students[key].join(', ')}`);
}
}
resolve(data);
}
});
});
}
module.exports = countStudents;