node.js - Nodejs FileReads Sync to Async -


i have 2 functions :

  1. one read file (post) : loadpost(name)
  2. one read files : loadposts()

obviously loadposts() calls loadpost(name).

both return final html.

ideally should write asynchronously.

the problem : i don't know how make asynchronously, need wait until file read before can continue.

here synchronous solution:

function loadpost(name){     var post = fs.readfilesync("_posts/"+name,'utf8');     // convert markdown html     var marked = mark(post);     return marked; }  function loadposts(){     var files = fs.readdirsync("_posts/");     var html;     for(var = 0; < files.length ; i++){         html += loadpost(files[i]);     }     return html; } 

something this, no third party libs necessary. simple really.

/*jshint node:true */  function loadposts(callback) {     'use strict';      var allhtml = ''; //declare html results variable within closure, can collect within functions defined within function      fs.readdir("_posts/", function (err, files) {          function loadpost(name) {             fs.read("_posts/" + name, 'utf8', function (err, data) {                  allhtml += mark(data);//append data file our html results variable                  if (files.length) {                     loadpost(files.pop()); //if have more files, launch async read.                 } else {                     callback(allhtml); //if we're out of files read, send program flow, using html gathered function parameter                 }             });         }          loadpost(files.pop());     }); }  function dosomethingwithhtml(html) {     'use strict';     console.log(html); }  loadposts(dosomethingwithhtml); 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -