node.js - Return value is undefined (should be string) -


i started develop stuff nodejs , got frustrating error.

i have function compile .jade .html

function compilejadefile(jadefile){     var pathtofile = "./index.jade";      fs.exists(pathtofile, function(exists){         if(exists){             fs.readfile(pathtofile, function(err, data){                                     var html = jade.compile(data)();                                     return html;             });         }     }); } 

everything works fine want serve compiled html. did this:

res.write(compilejadefile("index.jade")); 

(don't bother unused parameter of compilejadefile, used in original. shortened example)

now if log result of compilejadefile("index.jade") console says "undefined" :(

i searched google found nothing solves problem. can of me? i'm used code in c# or c++ maybe i'm missing or special javascript?

your code synchronous, code using asynchronous. problem when call compilejadefile function doesn't return anything, hence return value definition undefined.

you need make function asynchronous, too, , introduce callback , change method to:

function compilejadefile(jadefile, callback) {   var pathtofile = "./index.jade";    fs.exists(pathtofile, function(exists) {     if(exists){       fs.readfile(pathtofile, function(err, data) {         var html = jade.compile(data)();         callback(html);       });     }   }); } 

then can use this:

compilejadefile("index.jade", function (html) {   res.write(html);   res.end(); }); 

please note node.js-compliant callbacks callback should have err first parameter transfer errors. hence code should ideally be:

compilejadefile("index.jade", function (err, html) {   if (err) { throw err; }   res.write(html);   res.end(); }); 

then, of course need change call of callback to:

callback(null, html); 

hope helps :-).


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -