Return value is undefined (should be string)

I just started to develop some stuff with NodeJS and got a very frustrating error.

I have a function to compile .jade to .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 but now I want to serve the compiled html. So I did something like this:

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

(Don't bother about the unused parameter of compileJadeFile, it is used in the original. I just shortened it for this example)

Now if I log the result of compileJadeFile("index.jade") to the console it says "undefined" :(

I searched google for this but I found nothing that solves the problem. Can anyone of you help me? I'm used to code in C# or C++ so maybe I'm missing something or something special to Javascript?

Your code is synchronous, but the code you are using is asynchronous. The problem is that when you call your compileJadeFile function it actually doesn't return anything, hence its return value is by definition undefined.

You need to make the function itself asynchronous, too, and introduce a callback and change your 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 you can use it like this:

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

Please note that for fully Node.js-compliant callbacks a callback always should have err as its first parameter to transfer errors. Hence your code should ideally be:

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

Then, of course you need to change the call of the callback to:

callback(null, html);

Hope this helps :-).