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

Next.js中API路由操作JSON文件遇ENOENT错误求助

解决Next.js API路由中读取data.json时的ENOENT错误

问题原因

在Next.js环境下,使用__dirname解析文件路径会失效,核心原因是:

  • ES模块(Next.js默认启用)中没有内置__dirname变量,即使通过额外配置定义,也会因Next.js的构建打包机制,导致路径解析指向项目根目录而非函数文件所在的子目录(从错误信息可看出,程序正在项目根目录寻找data.json,而非函数所在的子文件夹)。

解决方案

方案1:用import.meta.url获取当前文件真实路径(推荐ES模块环境)

修改ReplaceData函数,通过import.meta.url和fileURLToPath工具,精准定位函数文件所在目录:

import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from 'url';

export async function ReplaceData(index, data) {
  try {
    // 获取当前文件的绝对路径
    const __filename = fileURLToPath(import.meta.url);
    // 获取当前文件所在的目录
    const __dirname = path.dirname(__filename);
    // 拼接data.json的完整路径
    const filePath = path.join(__dirname, "data.json");

    const existingData = await fs.readFile(filePath, "utf-8");
    const tempData = JSON.parse(existingData);

    tempData[index] = data;
    console.log("Reading Works: ", tempData);

    await fs.writeFile(filePath, JSON.stringify(tempData, null, 4));

    console.log("File successfully written!");
  } catch (error) {
    console.error("Error: ", error);
  }
}

方案2:用process.cwd()从项目根目录构建路径

如果你明确知道data.json相对于项目根目录的位置,可直接用process.cwd()(始终指向Next.js项目根目录)拼接路径。例如,若函数和data.json都在/utils文件夹下:

import fs from "fs/promises";
import path from "path";

export async function ReplaceData(index, data) {
  try {
    // 从项目根目录出发,拼接至data.json的路径
    const filePath = path.join(process.cwd(), "utils", "data.json");

    const existingData = await fs.readFile(filePath, "utf-8");
    const tempData = JSON.parse(existingData);

    tempData[index] = data;
    console.log("Reading Works: ", tempData);

    await fs.writeFile(filePath, JSON.stringify(tempData, null, 4));

    console.log("File successfully written!");
  } catch (error) {
    console.error("Error: ", error);
  }
}

额外提示

  • 若部署到Vercel等无服务器平台,文件写入无法持久化,这类平台的文件系统是临时的,如需持久化数据建议改用数据库或云存储服务。
  • 确认data.json确实存在于指定路径,且程序拥有读取/写入权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:52:57