快餐Web应用SSE活跃连接追踪及console.log日志转存TXT文件问题咨询
Hey there! I totally get where you're coming from—tracking SSE connections is crucial for making sure your kitchen staff gets real-time order updates without hiccups. Let's break down how to fix your logging issue and even level up your connection tracking.
First: Fixing the fs Module Approach (If You Want to Stick to Native Node.js)
Chances are the errors you're seeing come from either improper file handling (like not handling async operations correctly) or not using the right method for continuous logging. Here's the correct way to do it:
Option 1: Use a File Write Stream (Best for Continuous Logs)
Since SSE connections are long-lived, using a write stream avoids opening/closing the file every time you log something, which is more efficient and less error-prone:
const fs = require('fs'); const path = require('path'); // Create a write stream (append mode, so we don't overwrite logs) const logStream = fs.createWriteStream(path.join(__dirname, 'sse-connections.log'), { flags: 'a', // Append to file instead of overwriting encoding: 'utf8' }); // Helper function to log messages with timestamps function logSSEEvent(message) { const timestamp = new Date().toISOString(); logStream.write(`[${timestamp}] ${message}\n`); } // Use this in your SSE handlers // When a connection opens: logSSEEvent('Connection opened'); // When a message is sent: logSSEEvent('Message arrived: New order status update'); // When a connection closes: logSSEEvent('Connection closed');
Option 2: Use fs.appendFile (For Occasional Logs)
If you prefer appendFile, make sure to handle async properly (either with callbacks or async/await):
const fs = require('fs').promises; const path = require('path'); async function logSSEEvent(message) { const timestamp = new Date().toISOString(); const logEntry = `[${timestamp}] ${message}\n`; try { await fs.appendFile(path.join(__dirname, 'sse-connections.log'), logEntry); } catch (err) { console.error('Failed to write log:', err); } } // Usage is the same as above
Common pitfalls to avoid here:
- Forgetting to use
flags: 'a'(you'll overwrite the log file every time) - Not handling errors (fs operations can throw if you don't have write permissions, or the path doesn't exist)
- Using synchronous fs methods (like
fs.appendFileSync) in your SSE handler—this can block the event loop and slow down your app.
Second: Use a Dedicated Logging Library (Recommended)
Native fs works, but using a library like Winston or Pino will save you time handling edge cases (like log rotation, different log levels, formatting) and make your code cleaner. Here's a quick Winston example:
- Install Winston first:
npm install winston
- Set up your logger:
const winston = require('winston'); const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf(({ timestamp, level, message }) => { return `[${timestamp}] ${level.toUpperCase()}: ${message}`; }) ), transports: [ new winston.transports.File({ filename: 'sse-connections.log' }) ] }); // Usage in your SSE code: logger.info('Connection opened'); logger.info('Message arrived: Order #123 marked as "Preparing"'); logger.warn('Connection closed unexpectedly');
Winston automatically handles file appending, error handling, and you can even add a console transport alongside the file one for debugging.
Bonus: Tracking Active Connections (Beyond Just Logs)
Since you want to track active connections, don't rely solely on logs—maintain an in-memory store to keep track of live connections. This lets you check how many active kitchen terminals are connected at any time:
// Create a Set to store active SSE connections (Set automatically handles duplicates) const activeSSEConnections = new Set(); // When a client connects (in your SSE route): app.get('/kitchen/orders/sse', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); // Add the connection to our Set activeSSEConnections.add(res); logger.info(`New connection added. Active connections: ${activeSSEConnections.size}`); // Handle connection close req.on('close', () => { activeSSEConnections.delete(res); logger.info(`Connection closed. Active connections: ${activeSSEConnections.size}`); }); // Send initial status or updates here... });
This way, you have both persistent logs for auditing and a real-time count of active connections.
Troubleshooting Your Original fs Error
If you still run into issues with the native fs approach, check these:
- Verify the file path is correct (use
path.join(__dirname, 'your-log-file.log')to avoid relative path issues) - Make sure your Node.js process has write permissions for the directory where you're saving the log
- Check if the log file exists—fs.appendFile will create it if it doesn't, but createWriteStream will too (unless there's a permission issue)
Hope this helps get your kitchen order tracker running smoothly!
内容的提问来源于stack exchange,提问作者fabio

