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

使用Node.js FS模块读取字符串时遇JSON解析错误,求解决方案

解决FS读取JSON文件时的Unexpected Token错误

看起来你遇到的这个JSON解析错误,虽然你确认文件格式正确,但还是有几个常见的坑可以排查下:

1. 读取到了非JSON文件

你用fs.readdir读取了./Names目录下的所有文件,但目录里可能混了非JSON格式的文件(比如临时文件、.DS_Store、README之类的),这些文件的内容自然无法被JSON.parse解析,就会抛出错误。

解决方法:在遍历文件时过滤出.json后缀的文件:

const fs = require('fs');

fs.readdir('./Names', (err, files) => {
  if (err) throw err;
  // 只处理.json文件
  const jsonFiles = files.filter(file => file.endsWith('.json'));
  jsonFiles.forEach(file => {
    fs.readFile(`./Names/${file}`, 'utf8', (err, data) => {
      if (err) throw err;
      try {
        const jsonData = JSON.parse(data);
        console.log(jsonData);
      } catch (parseErr) {
        console.error(`解析文件${file}出错:`, parseErr);
      }
    });
  });
});

2. 文件编码或BOM问题

Windows系统下有些编辑器保存UTF-8文件时会自动加上BOM(字节顺序标记),而JSON.parse无法识别BOM,会把开头的BOM字符当成无效的JSON token(比如你看到的"Unexpected token r"可能就是BOM被解析成了奇怪的字符)。

解决方法:读取文件时指定编码为utf8,并手动去除BOM:

function stripBOM(content) {
  if (content.charCodeAt(0) === 0xFEFF) {
    return content.slice(1);
  }
  return content;
}

// 在readFile的回调里使用
const cleanedData = stripBOM(data);
const jsonData = JSON.parse(cleanedData);

3. 异步回调的错误处理问题

你的原始代码里没有对fs.readdir的错误做处理,而且一旦某个文件解析出错就会直接抛出错误终止程序。建议加上try/catch包裹JSON.parse,这样单个文件出错不会影响其他文件的处理,还能定位到具体出错的文件。

另外,也可以用fs.promises和async/await来简化异步代码,让逻辑更清晰:

const fs = require('fs').promises;
const path = require('path');

async function readAllJsonFiles() {
  try {
    const files = await fs.readdir('./Names');
    const jsonFiles = files.filter(file => file.endsWith('.json'));
    
    for (const file of jsonFiles) {
      const filePath = path.join('./Names', file);
      const data = await fs.readFile(filePath, 'utf8');
      const cleanedData = data.charCodeAt(0) === 0xFEFF ? data.slice(1) : data;
      const jsonData = JSON.parse(cleanedData);
      console.log(`解析${file}成功:`, jsonData);
    }
  } catch (err) {
    console.error('整体流程出错:', err);
  }
}

readAllJsonFiles();

先试试这些方法,应该能定位到问题所在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:23:16