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