我想把所有的
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);
}
}
有人发现第一种方法有什么问题吗?
谢谢您!