You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS如何读取日志文件Buffer并修改内容后完成JSON解析?

解决方案

首先你需要先将Buffer类型的文件内容转为字符串,再做格式修正,最后再做JSON解析,具体实现如下:

完整代码实现

const fs = require('fs');
let fileLogs = "./data/myfile.log";

fs.readFile(fileLogs, (err, fileLogsContent) => {
  if (err) {
    console.log("cannot read log file");
    return;
  }

  // 1. 将Buffer转为字符串,去除首尾空白字符
  const logStr = fileLogsContent.toString().trim();
  // 2. 拼接前缀[,替换末尾的逗号为],处理为标准JSON数组格式
  // 正则兼容末尾有无逗号、有无空白的场景,处理更稳妥
  const validJsonStr = `[${logStr.replace(/,+$/, '')}]`;
  // 3. 解析得到对象数组
  const logsContent = JSON.parse(validJsonStr);

  // 后续对logsContent对象数组执行操作
  console.log(logsContent);
});

可选优化方案(适合大日志文件)

如果日志文件体积较大,一次性读取全量内容转JSON容易占用过高内存,可以采用逐行读取的方案,单独解析每一行的JSON对象:

const fs = require('fs');
const readline = require('readline');

async function parseLogs() {
  const logsContent = [];
  const rl = readline.createInterface({
    input: fs.createReadStream("./data/myfile.log"),
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    // 去除每行首尾空白、末尾可能存在的逗号
    const trimmedLine = line.trim().replace(/,$/, '');
    if (!trimmedLine) continue; // 跳过空行
    logsContent.push(JSON.parse(trimmedLine));
  }
  return logsContent;
}

// 使用示例
parseLogs().then(logs => {
  // 后续操作
  console.log(logs);
}).catch(err => {
  console.log("日志解析失败", err);
});

内容的提问来源于stack exchange,提问作者delux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:09:03