2013-07-31 47 views
0

我基本上我有兩個功能:的NodeJS FileReads同步到異步

  1. 一個讀取文件(後):loadPost(name)
  2. 一個讀取所有文件:loadPosts()

顯然loadPosts()電話loadPost(name)

兩者都返回最終的html。

理想情況下,我應該寫它異步。

問題是:我不知道如何異步製作,因爲我需要等到文件完全讀取後才能繼續。

這裏是我的解決方案同步:

function loadPost(name){ 
    var post = fs.readFileSync("_posts/"+name,'utf8'); 
    // Convert Markdown to html 
    var marked = mark(post); 
    return marked; 
} 

function loadPosts(){ 
    var files = fs.readdirSync("_posts/"); 
    var html; 
    for(var i = 0; i < files.length ; i++){ 
     html += loadPost(files[i]); 
    } 
    return html; 
} 

回答

1

這樣的事情,沒有第三方庫必要的。真的很簡單。

/*jshint node:true */ 

function loadPosts(callback) { 
    'use strict'; 

    var allHtml = ''; //Declare an html results variable within the closure, so we can collect it all within the functions defined within this function 

    fs.readdir("_posts/", function (err, files) { 

     function loadPost(name) { 
      fs.read("_posts/" + name, 'utf8', function (err, data) { 

       allHtml += mark(data);//Append the data from the file to our html results variable 

       if (files.length) { 
        loadPost(files.pop()); //If we have more files, launch another async read. 
       } else { 
        callback(allHtml); //If we're out of files to read, send us back to program flow, using the html we gathered as a function parameter 
       } 
      }); 
     } 

     loadPost(files.pop()); 
    }); 
} 

function doSomethingWithHtml(html) { 
    'use strict'; 
    console.log(html); 
} 

loadPosts(doSomethingWithHtml); 
1

你想使用async.js包,讓您的生活更輕鬆。

function loadPost(name, callback) { 
    fs.readFile("_posts/+"name,{encoding:'utf8'},function(err, data) { 
    if(err) return callback(err); 
    // convert markdown to html 
    var marked = mark(post); 
    callback(false, marked); 
    }); 
} 

function loadPosts(cb) { 
    fs.readdir("_posts/", function(err, dir) { 
    if(err) return cb(err); 
    var html; 
    async.eachSeries(dir, function(one, callback) { 
     loadPost(one, function(err, post) { 
     if(err) return cb(err); 
     html += post; 
     callback(false); 
     }); 
    }, 
    // final callback 
    function(err) { 
     if(err) { console.log(err); cb(true); return; } 
     cb(false, html); 
    }); 
    }); 
} 
+0

這也適用,雖然恕我直言,異步是有點矯枉過正,這是一個相當簡單的例子。 – ChrisCM