vendredi 8 mai 2015

I'm getting a events.js:85 throw er; // Unhandled 'error' event

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.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);

When i visit http:/localhost:8001/socket.html, i get a blank screen in my browser, and my terminal says

Connection
events.js:85
      throw er; // Unhandled 'error' event
        ^
Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15)
    at /Users/Vik/Desktop/NodeJS/routingToDifferentUrls.js:22:34
    at fs.js:336:14
    at FSReqWrap.oncomplete (fs.js:99:15)

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!




Aucun commentaire:

Enregistrer un commentaire