tail-file.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /**
  2. * tail-file.js: TODO: add file header description.
  3. *
  4. * (C) 2010 Charlie Robbins
  5. * MIT LICENCE
  6. */
  7. 'use strict';
  8. const fs = require('fs');
  9. const { StringDecoder } = require('string_decoder');
  10. const { Stream } = require('readable-stream');
  11. /**
  12. * Simple no-op function.
  13. * @returns {undefined}
  14. */
  15. function noop() {}
  16. /**
  17. * TODO: add function description.
  18. * @param {Object} options - Options for tail.
  19. * @param {function} iter - Iterator function to execute on every line.
  20. * `tail -f` a file. Options must include file.
  21. * @returns {mixed} - TODO: add return description.
  22. */
  23. module.exports = (options, iter) => {
  24. const buffer = Buffer.alloc(64 * 1024);
  25. const decode = new StringDecoder('utf8');
  26. const stream = new Stream();
  27. let buff = '';
  28. let pos = 0;
  29. let row = 0;
  30. if (options.start === -1) {
  31. delete options.start;
  32. }
  33. stream.readable = true;
  34. stream.destroy = () => {
  35. stream.destroyed = true;
  36. stream.emit('end');
  37. stream.emit('close');
  38. };
  39. fs.open(options.file, 'a+', '0644', (err, fd) => {
  40. if (err) {
  41. if (!iter) {
  42. stream.emit('error', err);
  43. } else {
  44. iter(err);
  45. }
  46. stream.destroy();
  47. return;
  48. }
  49. (function read() {
  50. if (stream.destroyed) {
  51. fs.close(fd, noop);
  52. return;
  53. }
  54. return fs.read(fd, buffer, 0, buffer.length, pos, (err, bytes) => {
  55. if (err) {
  56. if (!iter) {
  57. stream.emit('error', err);
  58. } else {
  59. iter(err);
  60. }
  61. stream.destroy();
  62. return;
  63. }
  64. if (!bytes) {
  65. if (buff) {
  66. // eslint-disable-next-line eqeqeq
  67. if (options.start == null || row > options.start) {
  68. if (!iter) {
  69. stream.emit('line', buff);
  70. } else {
  71. iter(null, buff);
  72. }
  73. }
  74. row++;
  75. buff = '';
  76. }
  77. return setTimeout(read, 1000);
  78. }
  79. let data = decode.write(buffer.slice(0, bytes));
  80. if (!iter) {
  81. stream.emit('data', data);
  82. }
  83. data = (buff + data).split(/\n+/);
  84. const l = data.length - 1;
  85. let i = 0;
  86. for (; i < l; i++) {
  87. // eslint-disable-next-line eqeqeq
  88. if (options.start == null || row > options.start) {
  89. if (!iter) {
  90. stream.emit('line', data[i]);
  91. } else {
  92. iter(null, data[i]);
  93. }
  94. }
  95. row++;
  96. }
  97. buff = data[l];
  98. pos += bytes;
  99. return read();
  100. });
  101. }());
  102. });
  103. if (!iter) {
  104. return stream;
  105. }
  106. return stream.destroy;
  107. };