skip to Main Content

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?

hwo to do sos uisng termianl

3

Answers


  1. Chosen as BEST ANSWER
    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;
    

  2. 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');
    });
    
    Login or Signup to reply.
  3. 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}`);
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search