UNPKG

1.93 kBJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3
4common.register('tail', _tail, {
5 canReceivePipe: true,
6 cmdOptions: {
7 'n': 'numLines',
8 },
9});
10
11//@
12//@ ### tail([{'-n': \<num\>},] file [, file ...])
13//@ ### tail([{'-n': \<num\>},] file_array)
14//@ Available options:
15//@
16//@ + `-n <num>`: Show the last `<num>` lines of the files
17//@
18//@ Examples:
19//@
20//@ ```javascript
21//@ var str = tail({'-n': 1}, 'file*.txt');
22//@ var str = tail('file1', 'file2');
23//@ var str = tail(['file1', 'file2']); // same as above
24//@ ```
25//@
26//@ Read the end of a file.
27function _tail(options, files) {
28 var tail = [];
29 var pipe = common.readFromPipe();
30
31 if (!files && !pipe) common.error('no paths given');
32
33 var idx = 1;
34 if (options.numLines === true) {
35 idx = 2;
36 options.numLines = Number(arguments[1]);
37 } else if (options.numLines === false) {
38 options.numLines = 10;
39 }
40 options.numLines = -1 * Math.abs(options.numLines);
41 files = [].slice.call(arguments, idx);
42
43 if (pipe) {
44 files.unshift('-');
45 }
46
47 var shouldAppendNewline = false;
48 files.forEach(function (file) {
49 if (file !== '-') {
50 if (!fs.existsSync(file)) {
51 common.error('no such file or directory: ' + file, { continue: true });
52 return;
53 } else if (common.statFollowLinks(file).isDirectory()) {
54 common.error("error reading '" + file + "': Is a directory", {
55 continue: true,
56 });
57 return;
58 }
59 }
60
61 var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
62
63 var lines = contents.split('\n');
64 if (lines[lines.length - 1] === '') {
65 lines.pop();
66 shouldAppendNewline = true;
67 } else {
68 shouldAppendNewline = false;
69 }
70
71 tail = tail.concat(lines.slice(options.numLines));
72 });
73
74 if (shouldAppendNewline) {
75 tail.push(''); // to add a trailing newline once we join
76 }
77 return tail.join('\n');
78}
79module.exports = _tail;