There are two issues with what you have posted:
The
path
variable equals/socket.html
when the URLhttp://localhost:8001/socket.html
is requested, notsocket.html
; you need to update the case statement accordingly.The
fs.readFile
callback will not be able to write the response to back to the client (browser), asresponse.end();
will have already been called; you need to moveresponse.end()
into each of thecase
statements.
Here is the updated code:
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
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');
response.end();
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
response.end();
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
server.listen(8001);
io.listen(server);