94

The following code outputs the content of the index.html (it just contains the text hello world) to the browser. However, when I replace readFile() with readFileSync(), the request times out.

What am I missing? Is a different kind of buffer required? I am using node 0.61 and express 2.4.

var express = require('express');
var fs = require('fs');

var app = express.createServer(express.logger());

app.get('/', function(request, response) {
    fs.readFile('index.html', function(err, data){
        response.send(data.toString());
    });
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});
5
  • Aren't you supposed to call .end() when you're done sending? It's been a while since I used NodeJS.
    – user2437417
    Jul 11, 2013 at 22:57
  • 3
    What do you mean by when I replace readFile with readFileSync? The first one requires a callback while the other one does not. The code should be var data = fs.readFileSync('index.html');. The callback is never called, because readFileSync does not use it. That's where the timeout comes from. Assuming I understand it correctly.
    – freakish
    Jul 11, 2013 at 23:04
  • 1
    @CrazyTrain He's using Express. It does it for you.
    – freakish
    Jul 11, 2013 at 23:07
  • @freakish: Thanks. I never did use Express.
    – user2437417
    Jul 11, 2013 at 23:14
  • 1
    @freakish Thanks, can you recommend reading materials to understand node and callbacks better?
    – Ali
    Jul 13, 2013 at 16:07

3 Answers 3

107

fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

4
  • 49
    It's fine to call readFileSync to load your SSL certificates from disk as the server starts, as you need to block until those are ready. But, you're larger point is completely correct.
    – Dan Kohn
    Jul 12, 2013 at 2:52
  • 1
    @bryanmac thanks, Where can I learn more about which functions to use or not in a node/express app?
    – Ali
    Jul 13, 2013 at 16:10
  • 4
    The convention is all APIs are async and the exceptions use the format xxxSync. Avoid the xxxSync unless you are consciously meaning to be synchronous (startup or a script). A server should be async.
    – bryanmac
    Jul 22, 2013 at 23:32
  • another resource: blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop
    – bryanmac
    Jul 22, 2013 at 23:33
50
'use strict'
var fs = require("fs");

/***
 * implementation of readFileSync
 */
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");

/***
 * implementation of readFile 
 */
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

For better understanding run the above code and compare the results..

27

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.