1

I have set up a simple node.js server with the following code:

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){
                console.log(path);
                console.log(error);
                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);

Connecting to localhost:8001 works as expected.

However, when I attempt to connect to localhost:8001/socket.html, the server crashes and the following error is displayed to terminal:

events.js:141 throw er; // Unhandled 'error' event ^

Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:428:15) at /Users/Nikos/Desktop/hack_reactor/server.js:24:34 at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)

While debugging, console.log(error) returns null. Please explain why this is occurring.

2 Answers 2

3

The issue in your code is that fs.readFile is async function and thus response.end is run before response.write. After response.end the connection is closed and you cannot write anymore. The solution is simple. Simply call response.end when you done writing.

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');
            response.end();
            break;
        case '/socket.html':
            fs.readFile(__dirname + path, function(error, data){
                console.log(path);
                console.log(error);
                if (error){
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 404");
                    response.end();
                }
                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);
Sign up to request clarification or add additional context in comments.

Comments

-1

The problem com from the Async. of readFile You send response.end() before the end of fs.readFile

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){//<-----------+
                console.log(path);//                                          |
                console.log(error);//                                         |
                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();//<--------------------------This Happen before the end of |--^ | fs.readFile
});

server.listen(8001);

Try like 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;

    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){
                console.log(path);
                console.log(error);
                if (error){
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 404");
                    response.end();
                }
                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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.