【问题标题】:Nodejs FileReads Sync to AsyncNodejs FileReads 同步到异步
【发布时间】:2013-08-01 10:51:24
【问题描述】:

我基本上有两个功能:

  1. 一个读文件(post):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;
}

【问题讨论】:

    标签: node.js asynchronous file-io fs


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      您会希望使用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);
          });
        });
      }
      

      【讨论】:

      • 这也可以,虽然恕我直言异步在这里有点矫枉过正,这是一个相当简单的例子。
      猜你喜欢
      • 2019-06-14
      • 1970-01-01
      • 2016-12-14
      • 2014-01-05
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 2014-03-28
      相关资源
      最近更新 更多