pegasustech
pegasustech

Reputation: 67

Can not access socket.html

I want simulate client - server node.

Here is my server.js

var http = require("http");
var url = require('url');
var fs = require('fs');

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

    switch(path){
        case '/':
            response.writeHead(200, {'Content-Type': 'text/html'}); 
            response.write('hello world');
            break;
        case '/socket.html':
            fs.readFile(__dirname + path, function(error, data){

             /*  if (error){
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 404 1");

                }
                */

                    response.writeHead(200, {'Content-Type': 'text/html'});
                   // response.write("data terbaca 2"); 
                    response.write(data, "utf8");

            }); 
            response.writeHead(200, {'Content-Type': 'text/html'}); 
            response.write('hello world2 + ' + __dirname + ' ' + path);

            break;
        default:
            response.writeHead(404);
            response.write("opps this doesn't exist - 404 3");
            break;
    }
    response.end(); 
}); 

server.listen(8000); 

and here is my client html

<html>
<head></head>
<body>Ini Socket html lohhh</body>
</html>

My directory strucure is in D:/cobaa 1. server.js 2. socket.html

I node the server, and access the localhost:8000/socket.html and get

hello world2 + D:\cobaa /socket.html

can anybody get me the solution,please? Big thanks :)

Upvotes: 1

Views: 145

Answers (1)

user568109
user568109

Reputation: 48003

The catch here is you are finishing the response before you actually write the file contents. The fs.readFile is asynchronous, so the writing of the file contents is deferred until the read completes, so it reaches response.end() first and executes it.

The response should only be sent after file has been read. So put all your response handling inside the callback

        fs.readFile(__dirname + path, function(error, data){

            /*  if (error){
                response.writeHead(404);
                response.write("opps this doesn't exist - 404 1");
                }
            */
                response.writeHead(200, {'Content-Type': 'text/html'});
                response.write(data, "utf8");
                response.write('hello world2 + ' + __dirname + ' ' + path);
                response.end();
        }); 

Upvotes: 1

Related Questions