【问题标题】:Using fs.readdir and fs.statSync returns ENOENT, no such file or directory error使用 fs.readdir 和 fs.statSync 返回 ENOENT,没有这样的文件或目录错误
【发布时间】:2014-12-03 14:34:45
【问题描述】:

这行得通:

    var promise = new Future(),
        dirs = [],
        stat;
        

    Fs.readdir(Root + p, function(error, files){
        _.each(files, function(file) {
            //stat = Fs.statSync(file);
            //if ( stat.isDirectory() ) {
                dirs.push(file);
            //}
        });

        promise.return(dirs);
    });

这不是:

    var promise = new Future(),
        dirs = [],
        stat;
        

    Fs.readdir(Root + p, function(error, files){
        _.each(files, function(file) {
            stat = Fs.statSync(file);
            if ( stat.isDirectory() ) {
                dirs.push(file);
            }
        });

        promise.return(dirs);
    });

导致“错误:ENOENT,没有这样的文件或目录'fonts'”,但“fonts”是树中的第一个目录,并且确实存在。

我一定是错过了一些愚蠢的事情。我正在尝试仅返回文件夹/目录名称。

我在做的时候,有人知道如何返回所有级别的目录吗?

例如,结果可能是:

[
    "fonts",
    "fonts/font-awesome",
    "images",
    "images/somepath",
    "images/somepath/anotherpath"
]

在弄清楚我做错了什么之后,这是我的下一个目标。

【问题讨论】:

    标签: node.js npm fs


    【解决方案1】:

    readdir 将为您提供文件夹中条目的名称,而不是整个路径。这将起作用:

    stat = Fs.statSync(Root + p + "/" + file);
    

    整个代码:

    var promise = new Future(),
        dirs = [],
        stat,
        fullPath;
    
    
    Fs.readdir(Root + p, function(error, files){
        _.each(files, function(file) {
            fullPath = Root + p + "/" + file;
            stat = Fs.statSync(fullPath);
            if ( stat.isDirectory() ) {
                dirs.push(fullPath);
            }
        });
    
        promise.return(dirs);
    });
    

    【讨论】:

    • 这很好用。只要允许我就会接受答案。太感谢了。你不会碰巧知道如何解决我问题的最后一部分吧?检索所有级别的目录?
    • 这有点困难。您应该使用递归算法来执行此操作。每次遇到目录时,都会使用新路径再次调用列表器。列表器返回一个承诺,该承诺将使用它获得的数据来解决。当你得到的所有其他承诺都得到解决时,你就解决了这个承诺。
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2019-03-09
    • 2017-12-28
    • 2022-01-16
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多