node 根据文件名查找其在指定目录中的路径

时间:2020-12-30 22:12:26
 
var fs = require('fs');

function walk(path, it) {
    var dirList = fs.readdirSync(path);
    console.log(dirList.length);
    for (var i = 0; i < dirList.length; i++) {
        var item = dirList[i];
        if (fs.statSync(path + '/' + item).isDirectory()) {
            if (item == it) {
                return path + '/' + item;
            } else {
                var j = walk(path + '/' + item, it);
                if (j) {
                    return j;
                } else {
                    continue;
                }
            }
        } else if (fs.statSync(path + '/' + item).isFile()) {
            if (item == it) {
                return path + '/' + item;
            }
        }
    }
}