Using fs.readdir and fs.statSync returns ENOENT, no such file or directory error

青春壹個敷衍的年華 提交于 2019-12-04 01:43:04

问题


This works:

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

This does not:

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

Resulting in "Error: ENOENT, no such file or directory 'fonts'"

fonts is the first directory in the tree, and it does exist.

I've gotta be missing something silly. I'm trying to return folder/directory names only.

While I'm at it, does anyone know how to return all levels of directories?

For example, the result could be:

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

That is my next goal, after figuring out what I'm doing wrong.

I appreciate the help!


回答1:


readdir will give you the names of the entries in the folder, not the whole path. This will work:

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

The whole code:

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


来源:https://stackoverflow.com/questions/26265270/using-fs-readdir-and-fs-statsync-returns-enoent-no-such-file-or-directory-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!