Node.js写入JSON文件后读取报ENOENT错误的求助
Node.js fs读取JSON文件返回ENOENT错误的排查与解决
问题描述
我开发了一个网站爬虫程序,用fs.writeFile将数据存储为JSON格式,但另一个程序通过fs.readFile读取该JSON文件时,始终返回ENOENT: no such file or directory, open....错误。我已确认文件路径正确,目录中能看到目标文件,用require也能正常解析这个JSON,但使用fs相关方法就报错,哪怕提前用fs.access检查文件存在性也没用。
原始读取代码
fs.readFile("./json/productVariables.json","utf-8",(err, data) => { if (err) { console.log("could not read the JSON file " + err); } else { const productVariable = JSON.parse(data); }});
用fs.access检查存在性的代码
fs.access("productVariables.json", fs.constants.F_OK, (err) => { if (err) { console.log("JSON file doesn't exist " + err); } fs.readFile( "./json/productVariables.json", "utf-8", (err, data) => { if (err) { console.log("could not read the JSON file " + err); } else { const productVariable = JSON.parse(data); } } ) })
补充:改用fsPromises后的情况
写入代码
await fsPromises.writeFile( path.join(__dirname, "json", "productVarables.json"), JSON.stringify(variables), (err) => { if (err) { console.log("error while writing the JSON" + err); } else { console.log("successfuly written the JSON file"); } } );
读取代码
await fsPromises.readFile( path.join(__dirname, "json", "productVarables.json"), "utf-8", (err, data) => { if (err) { console.log(err); } else { console.log(data); } } );
报错信息
node:internal/process/promises:279 triggerUncaughtException(err, true /* fromPromise */); ^ [Error: ENOENT: no such file or directory, open 'D:\desktop\Project\Node\Scraper\json\productVariables.json'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'D:\\desktop\\Project\\Node\\Scraper\\json\\productVariables.json' }
问题根源与解决方法
- 文件名拼写错误:这是核心问题——你写入时用的文件名是
productVarables.json(少了一个字母i),但读取时(包括报错信息里的路径)用的是productVariables.json,导致读取的文件实际不存在。修正文件名拼写,保持写入和读取的文件名完全一致即可解决。 - 相对路径的隐患:早期使用
./json/productVariables.json这类相对路径时,Node.js的相对路径是基于**当前工作目录(CWD)**而非脚本所在目录,如果读取程序和爬虫程序的运行目录不同,就会出现路径错误。使用path.join(__dirname, ...)是正确的路径拼接方式,但前提是文件名拼写无误。 - fsPromises用法错误:
fsPromises的方法返回Promise,不需要传入回调函数,应该用try/catch处理错误,示例如下:// 正确写入方式 try { await fsPromises.writeFile( path.join(__dirname, "json", "productVariables.json"), JSON.stringify(variables) ); console.log("成功写入JSON文件"); } catch (err) { console.log("写入JSON出错:", err); } // 正确读取方式 try { const data = await fsPromises.readFile( path.join(__dirname, "json", "productVariables.json"), "utf-8" ); const productVariable = JSON.parse(data); console.log(productVariable); } catch (err) { console.log("读取JSON出错:", err); } - fs.access的冗余性:官方不推荐先用
fs.access检查文件再读取,因为会出现竞态条件——检查完成后到读取前的间隙,文件可能被删除或移动。直接调用fs.readFile并处理错误更可靠。
内容的提问来源于stack exchange,提问作者boom pow
相关产品推荐
相关产品推荐

