【问题标题】:Node.js FileSystem access returns ENOENT despite the file existing尽管文件存在,Node.js 文件系统访问返回 ENOENT
【发布时间】:2021-11-24 13:26:33
【问题描述】:

我有一个 node.js 函数,它使用 fs.access 检查文件是否存在,是否可读和可写:

function StackOverFlowFunction() {
try {
    fs.accessSync(`file://${__dirname}/config/config.ini`, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
    console.log(err);
}

尽管文件存在,

{ Error: ENOENT: no such file or directory, access 'file:///home/callcenter1/BookGenerator/config/config.ini'
at Error (native)
at Object.fs.accessSync (fs.js:248:11)
at Object.fs.accessSync (ELECTRON_ASAR.js:420:27)
at getConfig (/home/callcenter1/BookGenerator/main.js:12:12)
at Object.<anonymous> (/home/callcenter1/BookGenerator/main.js:18:10)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
errno: -2,
  code: 'ENOENT',
  syscall: 'access',
  path: 'file:///home/callcenter1/BookGenerator/config/config.ini' }

我在 Ubuntu 终端上使用了“打开链接”功能,它用 gedit 成功打开了文件。

有什么问题?

编辑 1:

我几乎可以肯定这条路是对的:

【问题讨论】:

  • 您是否检查其他文件,例如。在同一个文件夹中?我认为你走错了路。
  • 我看起来很奇怪file://${__dirname}/config/config.ini。你不能这样用吗:${__dirname}/config/config.ini

标签: javascript node.js electron


【解决方案1】:

使用正确的文件系统路径,没有方案:

fs.accessSync(`${__dirname}/config/config.ini`, ...)

【讨论】:

  • Electron 的win.loadURL('file://${__dirname}/app/app.html'); 工作正常。无论如何都试过了,错误仍然存​​在。
  • win.loadURL() 加载一个 URL; fs 用于文件系统操作。
  • 答案尚未完成,因为只有在删除$(__dirname) 时,该解决方案才能真正解决问题。
  • @Propolys 我拒绝了该编辑,因为它与问题的答案不匹配。您的问题中生成的路径(以及给出错误的路径)大部分是正确的,但仍在使用__dirname。您确定您使用的是方括号 (${__dirname}) 而不是圆括号 ($(__dirname))。
  • @Propolys __dirname 包含调用它的.js 文件的目录的绝对路径:)
【解决方案2】:

由于完全不同的原因,我遇到了类似的错误消息。如果您根据某些环境变量设置路径,则可能会发生这种情况,因为在 Windows 上的变量值中添加了额外的 (空格)。然后该消息将看起来很模糊,就像您确定不存在的现有文件一样:

{ "errorMessage":"The file at x:\\path\\to\\file.ext  does not exist, or it is not a file. ENOENT: no such file or directory, lstat 'x:\\path\\to\\file.ext '" }

注意file.extdoes 之间的 (双空格)。

我使用了类似的语法

SET "VARIABLE_NAME=VALUE-WHERE-EXTRA-SPACE-CAUSES-ERROR";

解决问题。在这里找到:https://superuser.com/a/1290292

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 2013-08-22
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    相关资源
    最近更新 更多