EisregenGruss36 EisregenGruss36 - 4 months ago 6
Javascript Question

Error when trying to acces parent folder in Electron/Node.js

I'm trying to check whether a path in a parent directory is a file or a directory.

My file system looks like this:


  • files/


    • html/


      • index.html


    • javascript/


      • index.js


    • test/


      • test.jpg





Electron is started from the parent directory of files/.
My code in the index.js file:

console.log(`file://${__dirname}/../test/test.jpg`);
console.log(fs.lstatSync(`file://${__dirname}/../test/test.jpg`).isFile());


When I start Electron I get two messages in the log. The first one is the path of the picture I want to access (test.jpg). When I paste this path into my browser, the picture is shown, so it is the correct path.
But the second message is an error:

Uncaught Error: ENOENT: no such file or directory, lstat


And then the same path in single quotation marks ('').

I used to have the index.js and the index.html file in the same path from which electron is started from (parent folder of files/) and it worked, so I guess that it has problems accesing a parent folder.
How can I solve this?

Answer

The Node fs module works with file paths, not URLs, so you need to pass a valid path to fs.lstatSync:

fs.lstatSync(`${__dirname}/../test/test.jpg`).isFile()