javascript – read from file in node js usign terminal error

const fs = require('fs');
const events = require('events');
const bf =require('buffer');

const REQUIRED_LINES = 10;  

function createWatcher(logFile) {
  const queue = [];
  const eventEmitter = new events.EventEmitter();
  const buffer = Buffer.alloc(bf.constants.MAX_STRING_LENGTH); 

  function readfile(curr, prev) {
    // Create a read stream from the file
    const readStream = fs.createReadStream(logFile, {
        start: prev.size,
        encoding: 'utf8'
    });

    let data="";

    readStream.on('data', chunk => {
        data += chunk;
    });

    readStream.on('end', () => {
        let logs = data.split('\n').slice(1);
        console.log("logs read: " + logs);

        if (logs.length >= REQUIRED_LINES) {
            logs.slice(-REQUIRED_LINES).forEach(elem => queue.push(elem));
        } else {
            logs.forEach(elem => {
                if (queue.length === REQUIRED_LINES) {
                    console.log("queue is full");
                    queue.shift();
                }
                queue.push(elem);
            });
        }
        eventEmitter.emit("process", logs);
    });

    readStream.on('error', err => {
        console.error("Error reading the file:", err);
    });
  }

    // Define the start function
  function startpoint() {
      fs.open(logFile, 'r', (err, fd) => {
        if (err) throw err;

        let data="";
        let logs = [];
        
        fs.read(fd, buffer, 0, buffer.length, 0, (err, readbytes) => {
          if (err) throw err;

          if (readbytes > 0) {
            data = buffer.slice(0, readbytes).toString();
            logs = data.split("\n");
            queue.length = 0;  // Clear the queue
            logs.slice(-REQUIRED_LINES).forEach((elem) => queue.push(elem));
          }

          fs.close(fd, (err) => {
            if (err) throw err;
          });
        });

        fs.watchFile(logFile, { interval: 1000 }, (curr, prev) => {
          readfile(curr, prev);
        });
      });
  }

  return {
    getLogs: function() {
      return queue;
    },
    emit: function(eventName, ...args) {
      eventEmitter.emit(eventName, ...args);
    },

    on: function(eventName, listener) {
      eventEmitter.on(eventName, listener);
    },
    off: function(eventName, listener) {
      eventEmitter.off(eventName, listener);
    },

    start: startpoint
  };
}
module.exports = createWatcher;

Read more here: Source link