| | const fs = require('fs'); |
| | const path = require('path'); |
| | const readline = require('readline'); |
| | const performanceMonitor = require('./performance'); |
| |
|
| | |
| | |
| | |
| | |
| | class LargeFileHandler { |
| | constructor(filePath) { |
| | this.filePath = filePath; |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | async generateTestFile(lines = 100000) { |
| | performanceMonitor.start('生成大文件'); |
| | return new Promise((resolve, reject) => { |
| | const stream = fs.createWriteStream(this.filePath); |
| | |
| | |
| | for (let i = 0; i < lines; i++) { |
| | |
| | const data = `${i},User_${i},${Date.now()},${Math.random() * 1000}\n`; |
| | if (!stream.write(data)) { |
| | |
| | |
| | } |
| | } |
| | |
| | stream.end(); |
| | stream.on('finish', () => { |
| | performanceMonitor.end('生成大文件'); |
| | console.log(`[大文件] 已生成测试文件: ${this.filePath}`); |
| | resolve(); |
| | }); |
| | stream.on('error', reject); |
| | }); |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | async processFileStream() { |
| | performanceMonitor.start('流式处理大文件'); |
| | |
| | const fileStream = fs.createReadStream(this.filePath); |
| | const rl = readline.createInterface({ |
| | input: fileStream, |
| | crlfDelay: Infinity |
| | }); |
| |
|
| | let lineCount = 0; |
| | let sumValue = 0; |
| |
|
| | for await (const line of rl) { |
| | lineCount++; |
| | |
| | const parts = line.split(','); |
| | if (parts.length >= 4) { |
| | sumValue += parseFloat(parts[3]); |
| | } |
| | } |
| |
|
| | console.log(`[大文件] 处理完成。总行数: ${lineCount}, Value总和: ${sumValue.toFixed(2)}`); |
| | performanceMonitor.end('流式处理大文件'); |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | async processFileSync() { |
| | console.log('[大文件] 警告:尝试一次性读取文件(不推荐用于大文件)...'); |
| | try { |
| | performanceMonitor.start('同步读取文件'); |
| | const data = fs.readFileSync(this.filePath, 'utf-8'); |
| | const lines = data.split('\n'); |
| | let sumValue = 0; |
| | |
| | lines.forEach(line => { |
| | if (!line) return; |
| | const parts = line.split(','); |
| | if (parts.length >= 4) { |
| | sumValue += parseFloat(parts[3]); |
| | } |
| | }); |
| | |
| | console.log(`[大文件] 同步处理完成。Value总和: ${sumValue.toFixed(2)}`); |
| | performanceMonitor.end('同步读取文件'); |
| | } catch (err) { |
| | console.error('[大文件] 读取失败:', err.message); |
| | } |
| | } |
| | } |
| |
|
| | module.exports = LargeFileHandler; |
| |
|