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