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 |
|
28 | function _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('');
|
77 | }
|
78 | return tail.join('\n');
|
79 | }
|
80 | module.exports = _tail;
|