Created
March 20, 2018 11:45
-
-
Save bbg/9318a9a5ed3a00c1e6348f74d8509ac4 to your computer and use it in GitHub Desktop.
nodejs dir to json
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
var fs = require('fs'); | |
var path = require('path'); | |
var diretoryTreeToObj = function(dir, done) { | |
var results = []; | |
fs.readdir(dir, function(err, list) { | |
if (err) | |
return done(err); | |
var pending = list.length; | |
if (!pending) | |
return done(null, {name: path.basename(dir), type: 'folder', children: results}); | |
list.forEach(function(file) { | |
file = path.resolve(dir, file); | |
fs.stat(file, function(err, stat) { | |
if (stat && stat.isDirectory()) { | |
diretoryTreeToObj(file, function(err, res) { | |
results.push({ | |
name: path.basename(file), | |
type: 'folder', | |
children: res | |
}); | |
if (!--pending) | |
done(null, results); | |
}); | |
} | |
else { | |
results.push({ | |
type: 'file', | |
name: path.basename(file) | |
}); | |
if (!--pending) | |
done(null, results); | |
} | |
}); | |
}); | |
}); | |
}; | |
var dirTree = ('./'); | |
diretoryTreeToObj(dirTree, function(err, res){ | |
if(err) | |
console.error(err); | |
console.log(JSON.stringify(res)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment