Last active
October 21, 2020 23:40
-
-
Save asyncanup/73a712fe5e2b62c9499526e075f5ca2d to your computer and use it in GitHub Desktop.
Node.js list directory tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
function tree(dir, shortName = dir, prefix = '') { | |
const ls = fs.readdirSync(dir); | |
const isDir = ls.map(item => fs.statSync(`${dir}/${item}`).isDirectory()); | |
const files = ls.filter((item, index) => !isDir[index]); | |
const dirs = ls.filter((item, index) => isDir[index]); | |
const filesPrefix = prefix + ' '; | |
console.log(); | |
console.log(`${prefix}${shortName || '.'}/`); | |
if (files.length) { | |
console.log(files.map(f => `${prefix} ${f}`).join('\n')); | |
} | |
dirs.forEach(item => tree(`${dir}/${item}`, `${shortName}${shortName ? '/' : ''}${item}`, prefix + ' ')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment