Created
December 1, 2018 20:41
-
-
Save Bigomby/fca703ccef0d79faa812355217ccaa21 to your computer and use it in GitHub Desktop.
This file contains 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'); | |
const DIRECTORY_COLOR = '\x1b[34m'; | |
const FILE_COLOR = '\x1b[32m'; | |
// ----------------------------------------------------------------------------- | |
// Formatting | |
// ----------------------------------------------------------------------------- | |
const buildPrefix = position => { | |
const parentLine = new Array(5) | |
.fill('│', 0, 1) | |
.fill(' ', 1, 2) | |
.join(''); | |
return new Array(position) | |
.fill(parentLine, 0, position + 5) | |
.concat('│─ ') | |
.join(''); | |
}; | |
const getColor = isDirectory => (isDirectory ? DIRECTORY_COLOR : FILE_COLOR); | |
const printItem = (name, color, prefix) => | |
// eslint-disable-next-line | |
console.log(`${color}${prefix}${name}`); | |
const printFile = (file, position = 0) => { | |
printItem(file.filename, getColor(file.isDirectory), buildPrefix(position)); | |
file.files && file.files.forEach(item => printFile(item, position + 1)); | |
}; | |
// ----------------------------------------------------------------------------- | |
// Helpers | |
// ----------------------------------------------------------------------------- | |
const setBasePath = basePath => filename => `${basePath}/${filename}`; | |
const isDirectory = filename => fs.lstatSync(filename).isDirectory(); | |
const isHidden = path => { | |
const [filename] = path.split('/').slice(-1); | |
return filename[0] === '.'; | |
}; | |
const byDirectoriesFirst = (a, b) => { | |
if (a.isDirectory) { | |
return -1; | |
} else if (b.isDirectory) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}; | |
const readFile = filename => ({ | |
filename, | |
hidden: isHidden(filename), | |
isDirectory: isDirectory(filename), | |
files: | |
isDirectory(filename) && | |
fs | |
.readdirSync(filename) | |
.map(setBasePath(filename)) | |
.map(readFile) | |
.filter(({ isHidden }) => !isHidden) | |
.sort(byDirectoriesFirst) | |
.reverse(), | |
}); | |
// ----------------------------------------------------------------------------- | |
// Main | |
// ----------------------------------------------------------------------------- | |
const file = readFile('/path/to/dir'); | |
printFile(file); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment