1 | var common = require('./common');
|
2 | var fs = require('fs');
|
3 |
|
4 | common.register('cat', _cat, {
|
5 | canReceivePipe: true,
|
6 | cmdOptions: {
|
7 | 'n': 'number',
|
8 | },
|
9 | });
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function _cat(options, files) {
|
31 | var cat = common.readFromPipe();
|
32 |
|
33 | if (!files && !cat) common.error('no paths given');
|
34 |
|
35 | files = [].slice.call(arguments, 1);
|
36 |
|
37 | files.forEach(function (file) {
|
38 | if (!fs.existsSync(file)) {
|
39 | common.error('no such file or directory: ' + file);
|
40 | } else if (common.statFollowLinks(file).isDirectory()) {
|
41 | common.error(file + ': Is a directory');
|
42 | }
|
43 |
|
44 | cat += fs.readFileSync(file, 'utf8');
|
45 | });
|
46 |
|
47 | if (options.number) {
|
48 | cat = addNumbers(cat);
|
49 | }
|
50 |
|
51 | return cat;
|
52 | }
|
53 | module.exports = _cat;
|
54 |
|
55 | function addNumbers(cat) {
|
56 | var lines = cat.split('\n');
|
57 | var lastLine = lines.pop();
|
58 |
|
59 | lines = lines.map(function (line, i) {
|
60 | return numberedLine(i + 1, line);
|
61 | });
|
62 |
|
63 | if (lastLine.length) {
|
64 | lastLine = numberedLine(lines.length + 1, lastLine);
|
65 | }
|
66 | lines.push(lastLine);
|
67 |
|
68 | return lines.join('\n');
|
69 | }
|
70 |
|
71 | function numberedLine(n, line) {
|
72 |
|
73 |
|
74 | var number = (' ' + n).slice(-6) + '\t';
|
75 | return number + line;
|
76 | }
|