Skip to content Skip to sidebar Skip to footer

My Http.createserver In Node.js Doesn't Work?

Hello guys i just started learning node.js today and search a lot off stuff on the internet , then try to code in node.js i use these two codes to show me the same result but the l

Solution 1:

request is an instance of http.IncomingMessage, which implements the stream.Readable interface.

Documentation at http://nodejs.org/api/stream.html#stream_event_end says:

Event: 'end'

This event fires when no more data will be provided.

Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling read() repeatedly until you get to the end.

var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
  console.log('got %d bytes of data', chunk.length);
})
readable.on('end', function() {
  console.log('there will be no more data.');
});

So in your case, because you don't use either read() or subscribe to the data event, the end event will never fire.

Adding

 request.on("data",function() {}) // a noop

within the event listener would probably make the code work.

Note that using the request object as a stream is only necessary for when the HTTP request has a body. E.g. for PUT and POST requests. Otherwise you can consider the request to have finished already, and just send out the data.

If the code your posting is taken literally from some other site, it may be that this code example was based on Node 0.8. In Node 0.10, there have been changes in how streams work.

From http://blog.nodejs.org/2012/12/20/streams2/

WARNING: If you never add a 'data' event handler, or call resume(), then it'll sit in a paused state forever and never emit 'end'. So the code you posted would have worked on Node 0.8.x, but does not in Node 0.10.x.


Solution 2:

The function you are applying to the HTTP server is the requestListener which supplies two arguments, request, and response, which are respectively instances of http.IncomingMessage and http.ServerResponse.

The class http.IncomingMessage inherits the end event from the underlying readable stream. The readable stream is not in flowing mode, so the end event never fires, therefore causing the response to never be written. Since the response is already writable when the request handler is run, you can just directly write the response.

var http = require('http');

http.createServer(function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.end('Hello HTTP!');
}).listen();

Post a Comment for "My Http.createserver In Node.js Doesn't Work?"