1 | var common = require('./common');
|
2 | var fs = require('fs');
|
3 |
|
4 | common.register('tail', _tail, {
|
5 | canReceivePipe: true,
|
6 | cmdOptions: {
|
7 | 'n': 'numLines',
|
8 | },
|
9 | });
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | function _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('');
|
76 | }
|
77 | return tail.join('\n');
|
78 | }
|
79 | module.exports = _tail;
|