Error reading file in node.js using terminal

When i want to read a file in node js it won’t display the file in the browser when I execute. and in the terminal says no such file or directory while I use the exact file path anyone can answer this why?

How to do sos using terminal?

New contributor

jack nelson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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;

New contributor

jack nelson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

const fs = require('fs');
const path = 'test.log'; 

let lineNumber = 1; // Initialize line number

const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

// Function to generate a random string of characters
const generateRandomString = (length) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(getRandomInt(0, characters.length - 1));
  }
  return result;
};

// Function to write a new line to the file
const writeToFile = () => {
  const randomString = generateRandomString(8); // Generate an 8-character long random string
  const content = `Line ${lineNumber}: ${randomString}`;

  // Append a newline before the new content to ensure it starts on a new line
  fs.appendFile(path, `n${content}`, 'utf8', (err) => {
    if (err) {
      console.error('Error appending to file:', err);
      return;
    }
    console.log(`Content successfully appended: ${content}`);

    // Increment line number
    lineNumber++;
  });
};

// Interval in milliseconds (e.g., 2000 ms = 2 seconds)
const interval = 1000;

// Run the write function continuously
setInterval(writeToFile, interval);
<!DOCTYPE html>
<html>
   <head><title>Tail -f</title></head>
   <script src="/socket.io/socket.io.js"></script>
   <script>
      var socket = io("ws://localhost:3000");
      socket.on('update-log', function(data){
          console.log(data);
          for(elem of data) document.getElementById('message-container').innerHTML +='<p>' + elem + '</br><p>';
      });
      socket.on('init',function(data){
        console.log(data);
        for(elem of data) document.getElementById('message-container').innerHTML +='<p>' + elem + '</br><p>';      })
   </script>
   <body>
       <h1>Log monitoring app</h1>
      <div id="message-container"></div>
      </body>
   </html>const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const path = require('path'); 
const Watcher = require('./watch2');
 
let watcher = new Watcher("test.log");

watcher.start();


app.get('/log', (req, res) => {
    console.log("request received");
    var options = {
        root: path.join(__dirname)
    };
     
    var fileName = 'index.html';
    res.sendFile(fileName, options, function (err) {
        if (err) {
            next(err);
        } else {
            console.log('Sent:', fileName);
        }
    });
})

io.on('connection', function(socket){
   // console.log(socket);
    console.log("new connection established:"+socket.id);

      watcher.on("process", function process(data) {
        socket.emit("update-log",data);
      });
      
      let data = watcher.getLogs();
      socket.emit("init",data);
   });

http.listen(3000, function(){
    console.log('listening on localhost:3000');
});

New contributor

jack nelson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

const express = require('express');
const { exec } = require('child_process');
const app = express();
const port = 3000;

// Define browser commands and paths
const browserPaths = {
  chrome: {
    start: 'google-chrome', // Use 'google-chrome-stable' if installed
    stop: 'pkill chrome',
    cleanup: 'sudo rm -rf ~/.config/google-chrome/Default/*'
  },
  firefox: {
    start: 'firefox', // Use 'firefox' command
    stop: 'pkill firefox',
    cleanup: 'sudo rm -rf ~/.mozilla/firefox/*.default-release/'
  }
};

// Root route
app.get('/', (req, res) => {
  res.send('Welcome to the Browser Service API. Use /start, /stop, /cleanup, or /geturl.');
});

// Start a browser with a specific URL
app.get('/start', (req, res) => {
  const { browser, url } = req.query;

  if (!browserPaths[browser] || !url) {
    return res.status(400).send('Invalid parameters');
  }

  const startCommand = `${browserPaths[browser].start} ${url}`;

  exec(startCommand, (error) => {
    if (error) {
      return res.status(500).send('Failed to start browser');
    }
    res.send('Browser started');
  });
});

// Stop a browser
app.get('/stop', (req, res) => {
  const { browser } = req.query;

  if (!browserPaths[browser]) {
    return res.status(400).send('Invalid browser');
  }

  exec(browserPaths[browser].stop, (error) => {
    if (error) {
      return res.status(500).send('Failed to stop browser');
    }
    res.send('Browser stopped');
  });
});

// Clean up browsing data
app.get('/cleanup', (req, res) => {
  const { browser } = req.query;

  if (!browserPaths[browser]) {
    return res.status(400).send('Invalid browser');
  }

  exec(browserPaths[browser].cleanup, (error) => {
    if (error) {
      return res.status(500).send('Failed to clean up browser');
    }
    res.send('Browser cleaned up');
  });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

New contributor

StriverBoii is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật