var fs = require("fs");
var path = require("path");
var traversalDir = function(path, directoryJson) {
fs.readdir(path,function(err, node) {
// exit if all nodes have no more child.
if (!node) {
return directoryJson;
}
node.forEach(function(filename) {
fs.stat(path + "/" + filename, function(err, info) {
// use the parent directory as the book name
var book = path.split("/").pop();
if (info.isDirectory()) {
// go dig deeper!
traversalDir(path + "/" + filename, directoryJson);
} else {
try {
// push the files inside the book directory into
// the directoryJson
directoryJson[book].push(filename);
} catch (err) {
// create the book node in the directoryJson
directoryJson[book] = Array();
directoryJson[book].push(filename);
console.log(JSON.stringify(directoryJson));
}
}
});
});
});
};
var root = path.join(__dirname);
console.log(JSON.stringify(traversalDir(path.join(root), {})));
在console.log
完成之前调用的最后一个function(traversalDir)
事件!
所以,我最终只能获得{}
值。但是,函数中的注销表明函数正常工作。