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

使用Node.js+Express读取同目录JSON文件提示不存在的问题

问题原因

Node.js 中 fs 模块使用相对路径时,路径是相对于进程启动的工作目录,而不是当前脚本文件所在的目录。比如你在项目根目录执行 node routes/customers.js,此时 ./ 指向的是项目根目录,而不是 routes 目录,自然找不到同目录的 customers.json。

解决方案

1. CommonJS 模块(使用 require)

用 __dirname(当前脚本的绝对目录路径)拼接文件名,确保路径绝对正确:

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

fs.readFile(path.join(__dirname, 'customers.json'), 'utf8', (err, data) => {
    if (err) {
        console.log("ERROR: " + err);
    } else {
        const jsonData = JSON.parse(data);
        res.json(jsonData); // 注意这里应该返回解析后的对象,而非原始字符串
    }
});

2. ES 模块(使用 import)

ES 模块不支持 __dirname,需要通过 import.meta.url 手动推导:

import fs from 'fs/promises'; // 推荐用 Promise 版本,更符合现代写法
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 用 async/await 写法更简洁
app.get('/customers', async (req, res) => {
    try {
        const data = await fs.readFile(join(__dirname, 'customers.json'), 'utf8');
        const jsonData = JSON.parse(data);
        res.json(jsonData);
    } catch (err) {
        console.log("ERROR: " + err);
        res.status(500).send('读取文件失败');
    }
});

额外检查项

  • 确认 customers.json 的文件名拼写完全一致(注意大小写,Linux/macOS 区分文件名大小写)
  • 检查文件是否真的存在于脚本所在目录,有没有被误删除或被版本控制工具忽略
  • 如果用了 nodemon 等工具重启服务,确保文件修改后已经被正确识别

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:07:15