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 | function _cat(options, files) {
|
30 | var cat = common.readFromPipe();
|
31 |
|
32 | if (!files && !cat) common.error('no paths given');
|
33 |
|
34 | files = [].slice.call(arguments, 1);
|
35 |
|
36 | files.forEach(function (file) {
|
37 | if (!fs.existsSync(file)) {
|
38 | common.error('no such file or directory: ' + file);
|
39 | } else if (common.statFollowLinks(file).isDirectory()) {
|
40 | common.error(file + ': Is a directory');
|
41 | }
|
42 |
|
43 | cat += fs.readFileSync(file, 'utf8');
|
44 | });
|
45 |
|
46 | if (options.number) {
|
47 | cat = addNumbers(cat);
|
48 | }
|
49 |
|
50 | return cat;
|
51 | }
|
52 | module.exports = _cat;
|
53 |
|
54 | function addNumbers(cat) {
|
55 | var lines = cat.split('\n');
|
56 | var lastLine = lines.pop();
|
57 |
|
58 | lines = lines.map(function (line, i) {
|
59 | return numberedLine(i + 1, line);
|
60 | });
|
61 |
|
62 | if (lastLine.length) {
|
63 | lastLine = numberedLine(lines.length + 1, lastLine);
|
64 | }
|
65 | lines.push(lastLine);
|
66 |
|
67 | return lines.join('\n');
|
68 | }
|
69 |
|
70 | function numberedLine(n, line) {
|
71 |
|
72 |
|
73 | var number = (' ' + n).slice(-6) + '\t';
|
74 | return number + line;
|
75 | }
|