node.js - Nodejs FileReads Sync to Async -
i have 2 functions :
- one read file (post) :
loadpost(name)
- 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
Post a Comment