t-comm
Version:
专业、稳定、纯粹的工具库
37 lines (34 loc) • 1.27 kB
JavaScript
import { getFs } from '../nodejs/fs.mjs';
import { getPath } from '../nodejs/path.mjs';
/**
* 同步递归收集目录下所有文件路径
* 递归遍历指定目录,收集所有文件的绝对路径到数组中
* @param {string} dirPath 目录路径
* @param {string[]} [fileList=[]] 用于累积结果的数组(可选,递归内部使用)
* @returns {string[]} 所有文件的绝对路径数组
* @example
* ```ts
* const files = collectFilesSync('/path/to/dir');
* // ['/path/to/dir/a.ts', '/path/to/dir/sub/b.ts', ...]
* ```
*/
function collectFilesSync() {
var dirPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var fileList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (!getFs().existsSync(dirPath)) {
console.log('[Not Exists]', dirPath);
return [];
}
var items = getFs().readdirSync(dirPath);
items.forEach(function (item) {
var fullPath = getPath().join(dirPath, item);
var stat = getFs().statSync(fullPath);
if (stat.isDirectory()) {
collectFilesSync(fullPath, fileList); // 递归进入子目录
} else {
fileList.push(fullPath); // 将文件路径加入数组
}
});
return fileList;
}
export { collectFilesSync };