Skip to content

Instantly share code, notes, and snippets.

@Lucifier129
Last active November 10, 2015 09:17
Show Gist options
  • Save Lucifier129/8f0e0a6b2838d30a275e to your computer and use it in GitHub Desktop.
Save Lucifier129/8f0e0a6b2838d30a275e to your computer and use it in GitHub Desktop.
read directory
/**
* module:tree
*
* example:
var join = require('path').join
var Tree = require('./tree')
var cwd = process.cwd()
new Tree(cwd, 'root').writeTo(join(cwd, 'tree.json')).then(function() {
console.log('done')
}).catch(console.error.bind(console))
*/
var fs = require('fs')
var join = require('path').join
var readDir = function(dirPath) {
return new Promise(function(resolve, reject) {
fs.readdir(dirPath, function(err, files) {
err ? reject(err) : resolve(files)
})
})
}
var getType = function(filename) {
return new Promise(function(resolve, reject) {
fs.stat(filename, function(err, stats) {
err ? reject(err) : resolve(stats.isDirectory() ? 1 : 0)
})
})
}
var writeFile = function(path, data) {
return new Promise(function(resolve, reject) {
fs.writeFile(path, data, function(err) {
err ? reject(err) : resolve()
})
})
}
var handlePromiseList = function(promiseList) {
var len = promiseList.length
if (len) {
return len > 1 ? Promise.all(promiseList) : promiseList[0]
} else {
return Promise.resolve(null)
}
}
function Tree(path, name, type) {
this.path = path
this.name = name
this.type = type || 'directory'
}
Tree.prototype.getChildren = function(path, files, types) {
var promiseList = []
types = Array.isArray(types) ? types : types ? [types] : []
this.children = types.map(function(type, index) {
var fileName = files[index]
var fullPath = join(path, fileName)
if (type === 1) {
var tree = new Tree(fullPath, fileName)
promiseList.push(tree.readDir(fullPath))
} else {
var tree = new Tree(fullPath, fileName, 'file')
}
return tree
})
return handlePromiseList(promiseList)
}
Tree.prototype.handleFiles = function(path, files) {
var promiseList = files.map(function(file) {
return getType(join(path, file))
})
return handlePromiseList(promiseList)
.then(this.getChildren.bind(this, path, files))
}
Tree.prototype.readDir = function(path) {
path = path || this.path
return readDir(path)
.then(function(files) {
return files.length ? this.handleFiles(path, files) : files
}.bind(this))
.catch(console.log.bind(console))
}
Tree.prototype.json = function() {
return JSON.stringify(this)
}
Tree.prototype.writeTo = function(path) {
return this.readDir().then(function() {
return writeFile(path, this.json())
}.bind(this))
}
module.exports = Tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment