I've been following this tutorial for an introduction on nodejs, but I'm having trouble returning something with response.write().
My server.js code works fine in returning "hello world" when I go to domain:8001, but navigating to domain:8001/socket.html returns a blank screen.
I've used console.log to check that the code to write "socket is here." is being executed, but I'm not sure why it isn't doing anything.
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;
console.log(__dirname);
console.log(path);
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("socket is here.");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
var io = require('socket.io').listen(server);
socket.html: (though it shouldn't matter what is contained in it)
<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>
You're ending the response before waiting for fs.readFile() to complete. Try this:
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;
console.log(__dirname);
console.log(path);
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("socket is here.");
}
response.end();
});
return;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
var io = require('socket.io').listen(server);
Also, doing fs.readFile(__dirname + path, ...); is potentially dangerous because someone could send a request like /../../../../../../etc/passwd. What you should do there instead is use the path module to resolve/normalize __dirname + path to an absolute path, and then ensure that that absolute path starts with the absolute path of your public directory.