UNPKG

1.84 kBJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3
4common.register('cat', _cat, {
5 canReceivePipe: true,
6 cmdOptions: {
7 'n': 'number',
8 },
9});
10
11//@
12//@ ### cat([options,] file [, file ...])
13//@ ### cat([options,] file_array)
14//@
15//@ Available options:
16//@
17//@ + `-n`: number all output lines
18//@
19//@ Examples:
20//@
21//@ ```javascript
22//@ var str = cat('file*.txt');
23//@ var str = cat('file1', 'file2');
24//@ var str = cat(['file1', 'file2']); // same as above
25//@ ```
26//@
27//@ Returns a string containing the given file, or a concatenated string
28//@ containing the files if more than one file is given (a new line character is
29//@ introduced between each file).
30function _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}
53module.exports = _cat;
54
55function 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
71function numberedLine(n, line) {
72 // GNU cat use six pad start number + tab. See http://lingrok.org/xref/coreutils/src/cat.c#57
73 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
74 var number = (' ' + n).slice(-6) + '\t';
75 return number + line;
76}