title: How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?
body: <p>I'm trying to get my head around synchronous versus asynchronous in Node.js, in particular for reading an HTML file.</p>
  <p>In a request handler, the synchronous version that I'm using, which works is the following:</p>
  <pre class="lang-js prettyprint-override"><code>    var fs = require(&quot;fs&quot;);
      var filename = &quot;./index.html&quot;;
      var buf = fs.readFileSync(filename, &quot;utf8&quot;);
      
      function start(resp) {
          resp.writeHead(200, { &quot;Content-type&quot;: &quot;text/html&quot; });
          resp.write(buf);
          resp.end();
      }
      
      exports.start = start; 
  </code></pre>
  <ol>
  <li>What would be the version using <code>readFile()</code>?</li>
  <li>I understand that <code>readFile</code> is asynchronous so theoretically, I should wait for the entire file to be read before rendering it, so should I introduce an <code>addListener</code>? I might be confusing different things.</li>
  </ol>
  <p>Edit: I have tried to refactor the code like this:</p>
  <pre class="lang-js prettyprint-override"><code>    var fs = require(&quot;fs&quot;);
      var filename = &quot;./index.html&quot;;
      function start (resp) {
          resp.writeHead(200, { &quot;Content-Type&quot;: &quot;text/html&quot; });
          fs.readFile(filename, &quot;utf8&quot;, function (err, data) {
              if (err) throw err;
              resp.write(data);
          });
          resp.end();
      }
  </code></pre>
  <p>I get a blank page. I guess it's because it should wait for all the data to be read, before <code>resp.write(data)</code>, how do I signal this?</p>