0

I am newish to Node.js. I am exploring about routing (code is shown bellow). When the client request a local page , in this case socket.html, the the client doesn't get the routed page rather it shows a blank page. I don't see any error from Node.js framework. Thanks for looking at it.

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

    switch(path){
        case '/':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('hello world');
            break;
        case '/socket2.html':
            fs.createReadStream(__dirname + path, function(error, data){
                if (error) {
                    console.log('there is error for ' + path);
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 404");
                }
                else {
                    console.log('sending file ' + data);
                    response.writeHead(200, { 'Content-Type': 'text/html' });
                    response.write(data);
                }
            });
            break;
        default:
            response.writeHead(404);
            response.write("opps this doesn't exist - 404");
            break;
    }
    console.log('send reponse');
    response.end();
});

console.log('Listening');
server.listen(8001);

console.log('Socket started for ' + path);
io.listen(server);

// socket2.html page content

<!DOCTYPE html>
<html>

    <head>
        <title></title>  
        <script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
    </head>


    <body>
        <script>
            var socket = io.connect();
        </script>
        <div>This is our socket2.html file</div>
    </body>
</html>

// Actual page content

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv="Content-Type" 
content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>
yesIcan
  • 1,441
  • 1
  • 11
  • 18
  • For an explanation of the problem, see here: http://stackoverflow.com/questions/20363617/http-status-code-200-but-page-does-not-load-node-js-socket-io-node-js-tutoria/26878550#26878550 – 7stud Nov 12 '14 at 23:32

1 Answers1

2

Please take a look on catberry.js or express frameworks.

I am sure nobody solves this task using node built-in HTTP server and switch operator. Maybe you just need a separate web server like nginx that serves static and pass some locations to node.js application to render some dynamic pages.