Nicolas4677
Nicolas4677

Reputation: 53

fs Error: EISDIR: illegal operation on a directory, read

I'm getting "Error: EISDIR: illegal operation on a directory, read" after trying to read the content of a .json. This is how I'm trying to access the file. I'm using the FileSystem of node js.

fs.readFile( path, ( err, fileData) => {

                if (err) {

                    throw err;
                }
                else {

                    return fileData;
                }
            });

While debugging I can see that the error is thrown before the if statement.

Any idea?

Upvotes: 3

Views: 20864

Answers (3)

I get the same error, after debugging a lot I finally figured out my path is not generated correctly, generating the path properly worked for me!

I recommend to generate file path before in separate variable using path package to get actual path, console.log your variable to see what actually path is:

import path from "path";

const { fileName } = req.query;
const filePath = path.resolve(__dirname, "../../../../your_folder");
console.log('filePath: ', filePath);

fs.readFile(`${filePath}\\${fileName}`, (err, fileData) => {
   if (err) {
     throw err;
   }
   else {
     console.log('fileData: ', JSON.parse(fileData));
     return fileData;
   }
 });

Note: I used double back slashes (because of string literal) to get one back slash '\' not forward slash '/'

Hope it helps!

Upvotes: 0

ThanhAnNguyen
ThanhAnNguyen

Reputation: 23

I have this error because it can not read my folder. so I trust read files and it working

Upvotes: 0

Osiris
Osiris

Reputation: 180

Maybe the path to the file is not the right one, make sure the path of your file looks like the one that appears in the following code:

const fs = require('fs');

fs.readFile('PATH_TO_YOUR_FILE/File_Name.json', (err, fileData) => {
    if (err) {
        throw err;
    } else {
        console.log(JSON.parse(fileData));
    }
});

Upvotes: 3

Related Questions