English 中文(简体)
使用终端读取节点.js 中的文件出错
原标题: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?
问题回答
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( ).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(" "); 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;
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, ` ${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); Tail -f

Log monitoring app

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 ); });
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}`); });




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签