|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | + |
| 6 | +const Promise = require('bluebird'); |
| 7 | +const P = require('bluebird-promisell'); |
| 8 | +const R = require('ramda'); |
| 9 | +const S = require('sanctuary'); |
| 10 | + |
| 11 | +// data Text = Buffer | String |
| 12 | +// readFile :: String -> String -> Promise Error Text |
| 13 | +const readFile = R.curry((encoding, filename) => |
| 14 | + new Promise((resolve, reject) => { |
| 15 | + fs.readFile(filename, {encoding: encoding}, (err, data) => { |
| 16 | + if (err != null) { |
| 17 | + reject(err); |
| 18 | + } else { |
| 19 | + resolve(data); |
| 20 | + } |
| 21 | + }); |
| 22 | + }) |
| 23 | +); |
| 24 | + |
| 25 | +// readFileWithDirAndName :: String -> String -> String -> Promise Error String |
| 26 | +const readFileWithDirAndName = R.curry((encoding, dir, name) => { |
| 27 | + const filePath = path.join(dir, name); |
| 28 | + return readFile(encoding)(filePath); |
| 29 | +}); |
| 30 | + |
| 31 | +// readFilesWithDirAndNames :: String -> [String] -> Promise Error [String] |
| 32 | +const readFilesWithDirAndNames = R.compose(P.traversep, readFileWithDirAndName); |
| 33 | + |
| 34 | +// concatFiles :: String -> Promise Error String |
| 35 | +const concatFiles = dir => { |
| 36 | + const indexFileP = readFileWithDirAndName('utf8', dir, 'index.txt'); |
| 37 | + const fileNamesP = P.liftp1(S.lines)(indexFileP); |
| 38 | + const readFilesWithNames = readFilesWithDirAndNames('utf8', dir); |
| 39 | + const filesP = P.liftp1(readFilesWithNames)(fileNamesP); |
| 40 | + return P.liftp1(R.join(''))(filesP); |
| 41 | +}; |
| 42 | + |
| 43 | + |
| 44 | +const main = () => { |
| 45 | + concatFiles(process.argv[2]) |
| 46 | + .then(data => { |
| 47 | + process.stdout.write(data); |
| 48 | + process.exit(0); |
| 49 | + }, |
| 50 | + err => { |
| 51 | + process.stderr.write(String(err) + '\n'); |
| 52 | + process.exit(1); |
| 53 | + }); |
| 54 | +}; |
| 55 | + |
| 56 | +if (process.mainModule.filename === __filename) main(); |
0 commit comments