text-like-read.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const { existsSync, createReadStream } = require('fs');
  2. const { createInterface } = require('readline');
  3. class TextLikeRead {
  4. constructor(options = { maxLines: 400, maxLength: 20 * 1000 }) {
  5. this.options = options;
  6. }
  7. read(file = '') {
  8. return new Promise((resolve, reject) => {
  9. if (typeof file !== 'string') {
  10. reject(new Error('File path must be a string'));
  11. }
  12. if (!existsSync(file)) {
  13. reject(new Error('The file does not exist'));
  14. }
  15. let remainLines = this.options.maxLines;
  16. let remainLength = this.options.maxLength;
  17. let text = '';
  18. const readStream = createReadStream(file, {
  19. encoding: 'utf-8',
  20. });
  21. const readLineStream = createInterface({
  22. input: readStream,
  23. setEncoding: 'utf-8',
  24. });
  25. readLineStream.on('line', (line) => {
  26. const lineLength = line.length;
  27. if (lineLength > remainLength) {
  28. line = line.substring(0, remainLength);
  29. remainLength = 0;
  30. } else {
  31. remainLength -= lineLength;
  32. }
  33. remainLines--;
  34. text += `${line}\n`;
  35. if (remainLines <= 0 || remainLength <= 0) {
  36. text += '...\n';
  37. readLineStream.close();
  38. readStream.close();
  39. }
  40. });
  41. readLineStream.on('close', (err) => {
  42. if (err) {
  43. reject(err);
  44. }
  45. resolve(text);
  46. });
  47. });
  48. }
  49. }
  50. exports.TextLikeRead = TextLikeRead;