Using fs.readdir and fs.statSync returns ENOENT, n

2019-06-03 20:13发布

问题:

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


标签: node.js npm fs