最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fs Error: EISDIR: illegal operation on a directory, read - Stack Overflow

programmeradmin11浏览0评论

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?

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?

Share Improve this question asked Apr 13, 2020 at 2:47 Nicolas4677Nicolas4677 531 gold badge1 silver badge5 bronze badges 1
  • 3 That error sounds like your path is a directory, not a file. You need to pass a path that points to a file to fs.readFile(). You should also know that neither throw err or return fileData are going to do anything useful. That returns data back into the file system code who called your callback, not back to the caller of your parent function. – jfriend00 Commented Apr 13, 2020 at 3:10
Add a ment  | 

3 Answers 3

Reset to default 3

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

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

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 remend 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!

发布评论

评论列表(0)

  1. 暂无评论