无法从目录中递归获取所有文本文件名

时间:2019-01-03 08:24:51

标签: javascript node.js recursion

我试图以递归方式(即搜索所有子文件夹)从目录中提取所有txt文件:

let fs = require("fs");

function getPathNames(dirName) {
    let pathNames = [];
    for (let fileName of fs.readdirSync(dirName)) {
        let pathName = dirName + "/" + fileName;
        if (fs.statSync(pathName).isDirectory())
            pathNames.concat(getPathNames(pathName));
        else if (pathName.endsWith(".txt"))
            pathNames.push(pathName);
    }
    return pathNames;
}

但是,当我调用getPathNames(".")时,我只会得到第一个文件的名称。

如果我从函数中取出返回值,而是更新一个全局变量,则效果很好:

let fs = require("fs");

let pathNames = [];

function getPathNames(dirName) {
    for (let fileName of fs.readdirSync(dirName)) {
        let pathName = dirName + "/" + fileName;
        if (fs.statSync(pathName).isDirectory())
            getPathNames(pathName);
        else if (pathName.endsWith(".txt"))
            pathNames.push(pathName);
    }
}

有人发现第一种方法有什么问题吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

好吧,concat并不是就位突变,而是返回一个新数组,所以我想你应该这样做

pathNames = pathNames.concat(getPathNames(pathName));