Node.js读取本地cpp文件遇ENOENT错误:方法正确性及修复方案
解决Node.js读取cpp文件时的ENOENT错误
嘿,你的核心思路是对的——用fs.readFileSync读取文件内容完全没问题,报错的根源是文件路径不对或者文件名拼写错误,咱们一步步来修复:
先排查最容易犯的错误:文件名/路径拼写
看你给出的错误信息:
Error: ENOENT: no such file or directory, open 'C:\Users\Heba\WebstormProjects\wrfile\sever.cpp'
但你写的代码里读的是code.cpp,这里明显出现了文件名不一致(sever.cpp vs code.cpp)!先去C:\Users\Heba\WebstormProjects\wrfile目录下确认:
- 目标文件到底叫什么?是
code.cpp还是sever.cpp? - 文件是不是真的存在这个目录里?
用绝对路径避免相对路径的坑
如果文件名确认没错,那大概率是相对路径的问题:Node.js里的相对路径是相对于你启动脚本的工作目录,而不是脚本文件本身所在的目录。比如你在别的文件夹运行node WebstormProjects/wrfile/app.js,相对路径就会出错。
推荐用path模块拼接绝对路径,这是最可靠的方式:
const fs = require('fs'); const path = require('path'); // __dirname 表示当前脚本(app.js)所在的目录 const cppFilePath = path.join(__dirname, 'code.cpp'); try { // 读取文件内容 const fileContent = fs.readFileSync(cppFilePath, 'utf8'); console.log(fileContent); // 顺便帮你实现行数统计 const lineCount = fileContent.split('\n').length; console.log(`这份cpp文件的总行数是:${lineCount}`); } catch (err) { console.error('读取文件时出错:', err.message); }
扩展:统计多个目录下的cpp文件行数
如果你要遍历不同目录统计所有cpp文件的行数,可以用fs.readdirSync递归遍历目录,举个简单的递归例子:
const fs = require('fs'); const path = require('path'); function countCppLines(dirPath) { let totalLines = 0; const files = fs.readdirSync(dirPath); files.forEach(file => { const fullPath = path.join(dirPath, file); const stats = fs.statSync(fullPath); if (stats.isDirectory()) { // 递归处理子目录 totalLines += countCppLines(fullPath); } else if (path.extname(file) === '.cpp') { // 处理cpp文件 const content = fs.readFileSync(fullPath, 'utf8'); const lines = content.split('\n').length; totalLines += lines; console.log(`${fullPath}:${lines}行`); } }); return totalLines; } // 替换成你要统计的根目录 const rootDir = path.join(__dirname, 'your-project-folder'); const total = countCppLines(rootDir); console.log(`所有cpp文件总行数:${total}`);
内容的提问来源于stack exchange,提问作者Heba
相关产品推荐
相关产品推荐

