forked from slavaGanzin/async-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coroutines-co.js
48 lines (40 loc) · 1.18 KB
/
coroutines-co.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
44
45
46
47
48
'use strict';
const fs = require('fs');
const path = require('path');
const co = require('co');
const R = require('ramda');
const S = require('sanctuary');
// readFile :: String -> String -> Promise Error String
const readFile = R.curry((encoding, filename) =>
new Promise((res, rej) => {
fs.readFile(filename, {encoding: encoding}, (err, data) => {
if (err != null) {
rej(err);
} else {
res(data);
}
});
})
);
// readFiles :: String -> [String] -> Promise Error [String]
const readFiles = R.curry((encoding, filenames) =>
Promise.all(R.map(readFile(encoding), filenames))
);
const main = () => {
const pathTo = (filename) => path.join(process.argv[2], filename);
co(function*() {
const index = yield readFile('utf8', pathTo('index.txt'));
const filenames = S.lines(index).map(pathTo);
const results = yield readFiles('utf8', filenames);
return results.join('');
})
.then(data => {
process.stdout.write(data);
process.exit(0);
},
err => {
process.stderr.write(String(err) + '\n');
process.exit(1);
});
};
if (process.mainModule.filename === __filename) main();