如何解决Error: ENOENT: 找不到文件或目录,无法打开login.json?
解决Error: ENOENT: no such file or directory, open 'login.json'问题
遇到这个报错本质是程序找不到指定的login.json文件,按以下步骤排查解决:
核对文件路径与位置
用相对路径'login.json'时,程序会在当前工作目录而非脚本所在目录查找文件。可以先打印当前工作目录确认:console.log(process.cwd()); // Node.js环境下执行该代码若文件不在当前工作目录,要么将
login.json移至该目录,要么改用绝对路径定位:const path = require('path'); const loginFilePath = path.join(__dirname, 'login.json'); // __dirname指向当前脚本所在目录检查文件本身的有效性
- 手动前往目标目录确认
login.json是否存在,注意区分文件名大小写(Linux/macOS系统严格区分,Login.json与login.json会被视为不同文件) - 排查文件是否被误删除、重命名,或是创建时拼写错误
- 手动前往目标目录确认
自动创建缺失文件(按需)
如果login.json是程序运行时需要生成的文件,可添加逻辑先判断文件是否存在,不存在则创建初始内容:const fs = require('fs').promises; const path = require('path'); async function ensureLoginFileExists() { const filePath = path.join(__dirname, 'login.json'); try { await fs.access(filePath); } catch { // 创建带初始结构的JSON文件 await fs.writeFile(filePath, JSON.stringify({ username: '', password: '' }, null, 2)); } return filePath; } // 使用示例 ensureLoginFileExists().then(filePath => { // 在此处执行文件读取操作 });
内容的提问来源于stack exchange,提问作者Ton
相关产品推荐
相关产品推荐

