【问题标题】:NodeJS fs.statSync(...).isDirectory() returns true for fileNodeJS fs.statSync(...).isDirectory() 为文件返回 true
【发布时间】:2017-07-21 21:29:30
【问题描述】:

尝试使用以下答案中的代码: https://stackoverflow.com/a/24594123/3951987

为我的目录中的文件返回 true。

为了提供更多上下文,这里有一些基本代码来描述我的实现:

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

在我的项目中,我有:

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

不知何故,即使应用了给定的过滤器,上述 getDirs 函数仍将 manifest.json 作为目录返回。

其他人有这个吗?有什么想法吗?

其他信息

我已将 getDirs 函数修改为以下内容:

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

这个的输出是:

getDirs a_path = <pathtoproject>/example
test
true
manifest.json
true

【问题讨论】:

    标签: node.js path fs


    【解决方案1】:

    变化:

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

    到:

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

    否则你声明a_path,而不是a_dir

    fs.statSync 接受一个参数 - 请参阅文档:

    【讨论】:

    • 呃,这么小的疏忽让我头疼……先生发现得很好:)
    • 回过头来看,由于我不需要编译我的绝对路径,所以我使用的示例有 fs.statSync(path.join(... 其中,我直接传递路径
    • @N15M0_jk 是的,您的第一个示例适用于:.filter(file =&gt; fs.statSync(path.join(a_path, file)).isDirectory());
    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2019-07-14
    • 2019-02-22
    • 2017-01-28
    • 2016-01-20
    相关资源
    最近更新 更多