简体   繁体   中英

Node.js FileSystem access returns ENOENT despite the file existing

I have a node.js function which uses fs.access to check if a file exists, is readable and writable:

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);
}

despite the file EXISTING,

{ 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' }

I used the "Open Link" function from the Ubuntu terminal and it opened the file with gedit successfully.

What's the issue?

Edit 1:

I'm almost sure the path is right:

在此处输入图片说明

使用正确的文件系统路径,而不使用方案:

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

I faced similar error message due to completely different reason. If you set path based on some env variables, this can happen because an extra (space) added to the variable value on Windows. Then the message will look quite obscure, like an existing file you sure about does not exist:

{ "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 '" }

Notice the (double space) between file.ext and does .

I used syntax like

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

to fix the issue. Found that here: https://superuser.com/a/1290292

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM