如何在recursion之后正确地返回值?

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), {}))); 

function(traversalDir)完成之前调用最后一个console.log东西!

所以,我最终只能得到{}值。 但是,函数内的注销表示该函数正常工作。