als-file-list
Version:
Generates filtered and sorted list of all file paths in a directory and its subdirectories.
39 lines (35 loc) • 1.55 kB
JavaScript
const fs = require('fs');
const path = require('path');
const {checkWhere,sortAndSelect,validateOptions,addError,notExistsSync} = require('./utils')
async function fileList(dirPath,options={}, errors = []) {
let { level, where, select,limit,skip,sort } = validateOptions(dirPath,options)
if(await notExistsSync(dirPath,errors)) return []
let n = 0, skiped = 0;
let result = [];
if(select !== undefined) select = select.trim().split(' ').filter(s => s !== '')
function readFiles(basePath, curLevel = 0) {
if(n >= limit) return
const files = fs.readdirSync(basePath);
for (const file of files) {
const currentPath = path.join(basePath, file);
const relativePath = path.relative(dirPath, currentPath).replace(/\\/g, '/');
try {
const stats = fs.statSync(currentPath)
const isDir = stats.isDirectory()
if(!checkWhere(where, relativePath, stats, isDir, errors)) continue
if (isDir) {
if(curLevel < level) readFiles(currentPath, curLevel + 1);
} else if(!sort) {
if(skiped < skip) skiped++
else if(n <= limit) {
result.push({relativePath,stats});
n++
}
} else result.push({relativePath,stats});
} catch (error) { addError(error, { relativePath }, errors) }
}
}
readFiles(dirPath);
return sortAndSelect(sort,result,skip,limit,select)
}
module.exports = fileList