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

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?

This question is related to node.js callback readfile fs

The answer is


This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to callback

When to use React setState callback How to send an HTTP request with a header parameter? javascript function wait until another function to finish What is the purpose of willSet and didSet in Swift? How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? Aren't promises just callbacks? How do I convert an existing callback API to promises? How to access the correct `this` inside a callback? nodeJs callbacks simple example Callback after all asynchronous forEach callbacks are completed

Examples related to readfile

How to read file with async/await properly? ReadFile in Base64 Nodejs How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? How do I read a file line by line in VB Script? open read and close a file in 1 line of code Reading file using fscanf() in C Where to put a textfile I want to use in eclipse?

Examples related to fs

Writing JSON object to a JSON file with fs.writeFileSync Using filesystem in node.js with async / await Write / add data in JSON file using Node.js Node.js Write a line into a .txt file NodeJS accessing file with relative path How to create full path with node's fs.mkdirSync? Read file from aws s3 bucket using node fs How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? nodejs get file name from absolute path? Node.js check if file exists