Skip to content

Instantly share code, notes, and snippets.

@drodsou
Last active May 1, 2020 18:14
Show Gist options
  • Save drodsou/11603d87731c3b03fbb27ef7eba8aadf to your computer and use it in GitHub Desktop.
Save drodsou/11603d87731c3b03fbb27ef7eba8aadf to your computer and use it in GitHub Desktop.
readdirSync but recursive - also known as walkDirSync (concise glob alternative)
const fs = require('fs');
const dir = (d) => fs.readdirSync(d, {withFileTypes:true})
.map(f=>f.isDirectory() ? dir(d + '/' + f.name) : d + '/' + f.name)
.flat();
// console.log(dir('somedir'));
// can use .filter() afterwards, of course
const fs = require('fs');
const path = require('path');
/**
* Also known as dirWalkSync.js
* returns array of string paths (ls -r, dir /s)
* includes both files an directories, these ones ending in 'path.sep'
*/
export function dirWalkSync (dir, filter, acc=[] ) {
dir = Array.isArray(dir) ? path.join(...dir) : dir;
for (let el of fs.readdirSync(dir, { withFileTypes: true })) {
let elName = path.join(dir,el.name, el.isDirectory() ? path.sep : '')
if ( !filter
|| (typeof filter === 'object' && filter.test(elName))
|| (typeof filter === 'function' && filter(elName))
) {
acc.push(elName)
}
if (el.isDirectory()) {
dirWalkSync(elName,filter,acc)
}
}
return acc;
}
dirWalkSync.sep = path.sep; // so you dont have to import path just for this
// -- EXAMPLES
//console.log(dirWalkSync([__dirname,'.']).join('\n')) // can pipe this in linux, e.g.
//console.log(dirWalkSync('.', /test\.js$/ ))
//console.log(dirWalkSync('.', e=>!e.match(/(\.git|node_modules)/) && e.endsWith(dirWalkSync.sep)));
/**
* old version
* Like readdirSync but recursive
* opt:
* type:dir
* depth: n
*/
function readdirSyncRecursive2(folder, opt={depth:9999} ) {
if (--opt.depth <=0) return []
let fs = require('fs')
let baseDir = folder.match(/\/$/) ? folder : folder + '/'
let filesAndFolders = fs.readdirSync(baseDir).map( f=>baseDir+f )
let files = []
filesAndFolders.forEach( f=>{
if (fs.statSync(f).isDirectory()) {
if (opt.type === 'dir') files.push(f)
files = files.concat( readdirSyncRecursive(f, Object.assign({},opt) )) // clone opt object to prevent mess
} else {
if (opt.type !== 'dir') files.push(f)
}
})
return files
}
// simple list files of a folder (not recursive)
const fs = require('fs');
const path = require('path');
let filesAndDirs = fs.readdirSync(path.join(__dirname,'/'));

// subdirectories only (not recursive)
let subdirs = fs.readdirSync(path.join(__dirname,'/')).filter(f=>fs.statSync(f).isDirectory());

// subdirectories only (node +10)
const fs = require('fs');
function getSubdirectories (baseDir) {
  return fs.readdirSync(baseDir, { withFileTypes: true })
    .filter(dirObj => dirObj.isDirectory())
    .map(dirObj => dirObj.name);
 }

// with glob, directories only (normal or recursive)
const glob = require('glob');   // npm install glob
let subdirs = glob.sync('__dirname',{mark:true}).filter(f=>f.endsWith('/'))   // mark adds '/' at the end of directories
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment