How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

Bondifrench picture Bondifrench · Apr 4, 2014 · Viewed 162.6k times · Source

I'm trying to get my head around synchronous versus asynchronous in Node.js, in particular for reading an HTML file.

In a request handler, the synchronous version that I'm using, which works is the following:

    var fs = require("fs");
    var filename = "./index.html";
    var buf = fs.readFileSync(filename, "utf8");
    
    function start(resp) {
        resp.writeHead(200, { "Content-type": "text/html" });
        resp.write(buf);
        resp.end();
    }
    
    exports.start = start; 
  1. What would be the version using readFile()?
  2. I understand that readFile is asynchronous so theoretically, I should wait for the entire file to be read before rendering it, so should I introduce an addListener? I might be confusing different things.

Edit: I have tried to refactor the code like this:

    var fs = require("fs");
    var filename = "./index.html";
    function start (resp) {
        resp.writeHead(200, { "Content-Type": "text/html" });
        fs.readFile(filename, "utf8", function (err, data) {
            if (err) throw err;
            resp.write(data);
        });
        resp.end();
    }

I get a blank page. I guess it's because it should wait for all the data to be read, before resp.write(data), how do I signal this?

Answer

webduvet picture webduvet · Apr 4, 2014
var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}