-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcharacterDistribution.js
More file actions
56 lines (52 loc) · 1.45 KB
/
characterDistribution.js
File metadata and controls
56 lines (52 loc) · 1.45 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
46
47
48
49
50
51
52
53
54
55
56
const { fork } = require('child_process');
const fs = require('fs');
const countsChars = (fileName, callback) => {
const counts = {};
const result = { fileName, counts };
if (!fs.existsSync(fileName)) return callback(result);
const reader = fs.createReadStream(fileName);
reader.setEncoding('utf8');
reader.on('data', text => {
const chars = text.split('');
const incrementCount = char => {
counts[char] = 1 + (counts[char] || 0);
}
chars.forEach(incrementCount);
});
reader.on('end', () => callback(result));
}
const worker = () => {
process.on('message', (fileName) => {
countsChars(fileName, (result) => process.send(result));
})
}
const showResult = msg => {
console.log(JSON.stringify(msg, null, 2));
}
const master = (count) => {
const children = [];
const sendRequest = (text) => {
const child = children.find(c => !c.isBusy);
if (!child) return console.log('All are busy');
child.isBusy = true;
child.send(text.trim());
}
for (let i = 0; i < count; i++) {
const child = fork(__filename);
child.on('message', msg => {
child.isBusy = false;
showResult(msg);
});
children.push(child);
}
process.stdin.setEncoding('utf8');
process.stdin.on('data', sendRequest);
}
//node characterDistribution.js 2
//todo.txt /* will give distribution of characters in todo.txt
const main = () => {
const count = +process.argv[2];
if (count) master(count);
else worker();
}
main();