Why can't I use response.write in fs.readFile?

Here is my code.

var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
path = path.substr(1);

switch(path){
    case '':
        response.writeHead(200, {'Content-Type':'text/html'});
        response.end();
        break;
    case 'socket.html':
        response.write("read file"); //works
        fs.readFile(__dirname + '\\' + path, function(error, data){
            if (error){
                response.writeHead(404); //this doesn't work
            }
            else{
                response.writeHead(200, {'Content-Type':'text/html'}); //doesn't work
                response.write("OK"); //doesn't work
            }
        });
        response.end();
        break;
    default:
        response.writeHead(404);
        response.end();
        break;
}
});

The server listens on port 8001 and when I visit http://myhost.com:8001/socket.html, I can only see "read file". Methods in response seems like broken in the callback function readFile. Can somebody tell my why and give me a solution? Thanks! (Forgive my poor English :) ).

You're ending the response too early. The function you pass to readFile is an asynchronous callback, which runs after the whole switch statement.