Search code examples
node.jshttpmodule

response written to page only on second request


var http = require('http');
var fs = require('fs');
var path = process.argv[2];
var str="";
function onRequest(request, response) {
    str += "";
    console.log("Request received" + path);
    fs.readdir(path, function(err, items) {
        str += items;
    });
    response.writeHead(200, {"Context-Type": "text/plain"});
    response.write(new Buffer(str).toString());
    response.end();
}
http.createServer(onRequest).listen(8000);

The above snippet creates a http server which gets a directory path from the user as argument. Make a http request to get the list of files available in the directory and send them back as a response.

The response is written to the page only on the second request. The page is shown empty on the first request.

Could anyone help. Thanks in advance!!


Solution

  • Javascript is non blocking, so

    response.writeHead(200, {"Context-Type": "text/plain"});
    response.write(new Buffer(str).toString());
    response.end();
    

    will be executed before

    str += items;
    

    With

    fs.readdir(path, function(err, items) {
        // Handle error
        str += items;
        response.writeHead(200, {"Context-Type": "text/plain"});
        response.write(new Buffer(str).toString());
        response.end();
    });
    

    it will send the response after readdir.

    And in Javascript the program will not be started for every new Request (like in PHP). So your global variable will be shared between all requests. If you don't want that put the var str=""; in onRequest.

    If you have multiple routes you also want to look into something like express, because the http module doesn't include routing.