2013-03-28 32 views
0

我想調用Node.js中的函數,獲取結果並將它們發送到模板。 results總是返回空。將變量發送到nodeJs中的jade模板引擎(同步)

怎麼了?

var replace = req.params.replace || ""; 
var find = req.params.find; 
var fs = require("fs"); 
var dir = "./public/sounds/"; 
var results = []; 

var readFiles = function (root) { 
    fs.readdir(root, function (err, files) { 
     if (err) { 
      console.log(err); 
      return; 
     } 
     files.forEach(function (file) { 
      console.log(root.concat(file)); 
      fs.stat(root.concat(file), function (err, stat) { 
       if (stat && stat.isDirectory()) { 
        readFiles(root.concat(file + "/")); 
       } 
      }); 
      if (file.indexOf(find) > 0) { 
       var oldPath = root.concat(file); 
       var newPath = oldPath.replace(find, replace).trim(); 
       console.log("Old Path: ", oldPath, " New Path: ", newPath); 
       fs.rename(oldPath, newPath); 
       results.push(newPath); 
      } 
     }) 

    }); 
}; 
readFiles(dir); 
res.jsonp({ 
    message: results 
}); 

回答

0
var results = []; 
...some async stuff... 
console.log(results); 

將打印空數組每一次,所以如何解決。

簡短的回答:

var async = require('async'); 
async.each(files, function (file) { ... }, 
    function (error, results) { 
    res.jsonp({ 
     message: results 
    }); 
    }); 

較長的答案,你的代碼分支笨拙所以它需要一些重組工作的權利。

var async = require('async'); 
var replace = req.params.replace || ""; 
var find = req.params.find; 
var fs = require("fs"); 
var dir = "./public/sounds/"; 


var readFiles = function (root, cb) { 
    var results = []; 
    fs.readdir(root, function (err, files) { 
     if (err) { 
      cb(err); 
      return; 
     } 
     aync.each(file, function (file, cb) { 
      console.log(root.concat(file)); 
      fs.stat(root.concat(file), function (err, stat) { 
       if (err) { 
        return cb(err); 
       } 
       if (stat && stat.isDirectory()) { 
        readFiles(root.concat(file + "/"), function (err, res) { 
         results = results.concat(res); 
         cb(err); 
        }); 
       } else { 
        if (file.indexOf(find) > 0) { 
         var oldPath = root.concat(file); 
         var newPath = oldPath.replace(find, replace).trim(); 
         console.log("Old Path: ", oldPath, " New Path: ", newPath); 
         fs.rename(oldPath, newPath); 
         results.push(newPath); 
        } 
        cb(); 
       } 
      }); 

     }, function (err) { 
      cb(err, results); 
     }); 

    }); 
}; 
readFiles(dir, function (err, results) { 
    res.jsonp({ 
    message: results 
    }); 
}); 

我還沒有測試過,所以讓我知道你是否有麻煩調試它。