Skip to content

Instantly share code, notes, and snippets.

@shilangyu
Created September 22, 2018 13:30
Show Gist options
  • Save shilangyu/22e71c3b5bc3c3681a124706ab007b92 to your computer and use it in GitHub Desktop.
Save shilangyu/22e71c3b5bc3c3681a124706ab007b92 to your computer and use it in GitHub Desktop.
Creates a json file listing all files and dirs from the caller dir (node.js)
const [path, fs] = ['path', 'fs'].map(require)
// config
const config = {
outputFile: {
name: 'files.json',
dir: './',
indent: 2
}
}
// path helpers
const getFolderName = path => {
const execed = /[\\\/]([^\\\/]+)[\\\/]?$/.exec(path)
if(execed)
return execed[1]
else
return new Error('incorrect path')
}
const isFolder = path => fs.lstatSync(path).isDirectory()
// CreateList
class CreateList {
constructor() {
this.fileTree = {}
this.listOut(process.cwd(), this.fileTree)
}
listOut(currPath, currTree) {
const dir = fs.readdirSync(currPath)
const currFolderName = getFolderName(currPath)
const folders = dir.filter(name => isFolder(path.join(currPath, name)))
const files = dir.filter(name => !folders.some(fName => fName === name))
currTree[currFolderName] = files
if(folders.length) {
const sub = {}
currTree[currFolderName].push(sub)
folders.forEach(name => {
this.listOut(
path.join(currPath, name),
sub
)
})
}
}
save(path, indent) {
fs.writeFileSync(path, JSON.stringify(this.fileTree, null, indent))
}
}
// app
const createList = new CreateList()
const { name, dir, indent } = config.outputFile
createList.save(path.join(dir, name), indent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment