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

Node.js使用fs模块读取文件时出现文件不存在错误求助

解决Node.js中fs.readFileSync读取文件出现ENOENT错误的问题

核心问题在于Node.js的相对路径解析逻辑:相对路径是基于你执行node命令时的当前工作目录(CWD),不是脚本文件所在的目录,这是很多开发者踩坑的点。

给你几个可靠的解决方法:

1. 使用绝对路径拼接(推荐,不受工作目录影响)

根据你使用的模块系统选择对应写法:

CommonJS 写法

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

// __dirname 是当前脚本文件所在目录的绝对路径
const filePath = path.join(__dirname, '../data/string.txt');
const content = fs.readFileSync(filePath, 'utf8');

ES 模块 写法

ES模块没有内置__dirname,需要手动通过import.meta.url生成:

import { readFileSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

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

const filePath = path.join(__dirname, '../data/string.txt');
const content = readFileSync(filePath, 'utf8');

2. 检查并修正当前工作目录

先在代码里打印当前工作目录,确认路径基准:

console.log(process.cwd());

比如你如果是在项目根目录(app文件夹的上级目录)执行node app/controller/appController.js,那相对路径应该写成app/data/string.txt,但这种方式依赖启动命令的位置,不推荐用于生产环境。

3. 排查基础问题

  • 确认文件名/路径没有大小写错误(Linux/macOS区分大小写,Windows不区分)
  • 检查文件确实存在,Node进程对该文件有读取权限
  • 确保没有拼写错误,比如把string.txt写成strng.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:57:02