Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS fs.statSync(...).isDirectory() returns true for file

Tags:

path

node.js

fs

Attempting to use the code from the following answer: https://stackoverflow.com/a/24594123/3951987

Returns true for a file inside a directory for me.

To provide more context, here's some basic code to describe my implementation:

getDirs = (a_path) => {
    return fs.readdirSync(a_path)
        .filter(file => fs.statSync(path.join(a_path, file)).isDirectory());
}

someCode = () => {
    let some_path = path.resolve(process.cwd(), "example");
    console.log(getDirs(some_path));
}

In my project, I have:

example/
- test/
- manifest.json
index.js

Somehow the getDirs function described above still returns manifest.json as a directory, even with the given filter applied.

Anyone else had this? Any ideas?

Additional Information

I've modified the getDirs function to the following:

getDirs = (a_path) => {
    console.log("getDirs a_path = "+a_path);
    let dirs = fs.readdirSync(a_path);

    for(let x = 0; x<dirs.length; x++){
        let a_dir = path.resolve(a_path, dirs[x]);
        console.log(dirs[x]);
        console.log(fs.statSync(a_path, a_dir).isDirectory());
    }
    return dirs;
};

The output for this is:

getDirs a_path = <pathtoproject>/example
test
true
manifest.json
true
like image 758
jarodsmk Avatar asked Mar 02 '17 08:03

jarodsmk


1 Answers

Change:

console.log(fs.statSync(a_path, a_dir).isDirectory());

to:

console.log(fs.statSync(a_dir).isDirectory());

Otherwise your stating the a_path, not a_dir.

fs.statSync takes one argument - see the docs:

  • https://nodejs.org/api/fs.html#fs_fs_statsync_path
like image 170
rsp Avatar answered Sep 19 '22 10:09

rsp