Reputation: 73
I was trying to follow a tutorial on creating a router with Node.js. Here is the code for the router..
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.readFileSync(__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);
When i visit http:/localhost:8001/socket.html, i get a blank screen in my browser, and my terminal says
Connection
fs.js:347
throw new TypeError('Bad arguments');
^
TypeError: Bad arguments
at Object.fs.readFileSync (fs.js:347:11)
at Server.<anonymous> (/Users/Vik/Desktop/NodeJS/routingToDifferentUrls.js:15:20)
at Server.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:491:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:343:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:529:20)
then exits.
Can anyone please explain why I am getting this error??? And yes, I have created my socket.html file, which displays nothing but simple text saying "this is our socket.html file."
Thanks a ton in advance for any help!
Upvotes: 1
Views: 786
Reputation: 2991
Well it looks like you are using fs.readFile
which is asynchronous. so response.end()
is being called before that finishes.hence your error message write after end
.You really want to be using fs.readFileSync to grab the contents of socket.html. like var data = fs.readFileSync.(__dirname + path)
Upvotes: 2