使用Node.js无法将chunk数据按正确格式推入数组如何解决
问题原因
你当前的代码直接将读取到的整块文件内容作为单个元素推入数组,没有做内容拆分、无效内容过滤,因此输出结果不符合预期。
解决方案
如果你的变更日志文件体积不大,推荐直接一次性读取文件后做内容处理,实现更简单:
const fs = require('fs'); // 读取文件内容并指定编码 const content = fs.readFileSync('../../../CHANGES', 'utf8'); const result = []; // 按换行符拆分得到所有行 const lines = content.split('\n'); for (let line of lines) { const trimmedLine = line.trim(); // 过滤空行、全是等号的分隔线 if (!trimmedLine || /^=+$/.test(trimmedLine)) continue; // 处理版本号+日期行(v开头的行) if (trimmedLine.startsWith('v')) { // 按任意数量空格拆分,得到版本号和日期两个独立字段 const [version, date] = trimmedLine.split(/\s+/); result.push(version); result.push(date); continue; } // 处理Changes:行,按需去掉末尾冒号 if (trimmedLine === 'Changes:') { // 需要保留冒号可直接改为 result.push(trimmedLine) result.push(trimmedLine.slice(0, -1)); continue; } // 更新条目直接推入数组 result.push(trimmedLine); } console.log(result);
如果需要处理超大体积的日志文件,避免内存占用过高,可以使用流式逐行读取方案:
const fs = require('fs'); const readline = require('readline'); // 创建逐行读取实例 const rl = readline.createInterface({ input: fs.createReadStream('../../../CHANGES', 'utf8'), crlfDelay: Infinity }); const result = []; // 逐行处理内容 rl.on('line', (line) => { const trimmedLine = line.trim(); if (!trimmedLine || /^=+$/.test(trimmedLine)) return; if (trimmedLine.startsWith('v')) { const [version, date] = trimmedLine.split(/\s+/); result.push(version); result.push(date); return; } if (trimmedLine === 'Changes:') { result.push(trimmedLine.slice(0, -1)); return; } result.push(trimmedLine); }); // 读取完成后输出结果 rl.on('close', () => { console.log(result); });
输出验证
上述代码运行后输出的数组结构和你要求的预期格式完全一致。
内容的提问来源于stack exchange,提问作者subhra_user
相关产品推荐
相关产品推荐

