title: node.js make code wait until the fs.readFile is completed
body: <p>I got a problem in node.js file system.
  here is my code. 
  my function always return a empty string.
  I'm wondering is there anyway to make my function stop execute until readFile method is completed.</p>
  
  <pre><code>var fs = require('fs');
  function myfun(filePath){
    var str = '';
    fs.readFile(filePath, function(err, data){
      if(err) throw err;
      str = data;
    });
    return str; //here, the variable str always return '' because the function doesn't wait for the readFile method complete.
  }
  </code></pre>
  
  <hr>
  
  <p>add explanation</p>
  
  <p>Actually I'm doing something like this:
  the function myfun is used for replace str
  you can see my code:</p>
  
  <pre><code>function fillContent(content) {
    var rex = /\&lt;include.*?filename\s*=\s*"(.+?)"\/&gt;/g;
    var replaced = fileStr.replace(rex, function (match, p1) {
      var filePath = p1
      var fileContent = '';
      fs.readFile(filePath, function (err, data) {
        if (err) {
          throw err;
        }
        fileContent = data;
      });
      return fileContent;
    });
    return replaced;// here, the return value is used for replacement
  }
  </code></pre>
  
  <p>I need a return value in the replace function, so this is why I didn't use a callback function</p>