i am newbie to node.js. I was trying to implement danielnill example tutorial
server.js
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');
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");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
io.listen(server);
socket.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect();
</script>
<div>This is our socket.html file</div>
</body>
</html>
when ever i am trying run this http://localhost:8001/socket.html
url from browser. Its goes to default case instead going to 'socket.html' case.
Pls help me to execute 'socket.html' case in this example.
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: