Unable to execute function at end of http request - node.js

I recreated a simple http server setup I found online (see below), but cannot get the request.on("end", ...) to work. It works fine if I comment that part out, but I really want to understand why it isn't working. Please help. Thanks!
Correct me if I'm wrong, but I think what's happening here is as follows:
var http = require('http'); pulls all "exports" from the node.js http module and allows them to be used in this node.js simple server code.
http.createServer instantiates an object of the http.Server class/type.
.listen(8080) opens the server for connections at port 8080 on localhost.
When a user attempts to connect at port 8080, the Server object emits a request event (which is itself another event.emitter object?). That event invokes the anonymous listener function and passes request object to it.
request.on("end", ...) adds a listener function to the request object that looks specifically for an eventName "end". If the end event is emitted by the request object, then the anonymous function is invoked (the response is written).
Here is the code I used: https://code.tutsplus.com/tutorials/nodejs-for-beginners--net-26314
var http = require("http");
http.createServer(function(request, response) {
request.on("end", function() {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end("Hello HTTP!");
});
}).listen(8080);

Related

Socket.io listening on port not working

So I have a very basic script which should only output a status code 200 when I visit my website on port 8081. But it doesn't seem to be working. Anybody knows why this is the case? I think it maybe has to do with ssl I am using, or am I forgetting something else?
//Begin config
var http = require('http');
var io = require('socket.io')(http);
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
I copied this from the internet to simply test if socket.io works correctly. I'm trying this on this website.
Thanks in advance!
Edit: I did run it using node script.js.
Use the http server as a variable and put the socket.io line to the end, change port:
var server = http.createServer(/*...your code...*/).listen(3000);
var io = require('socket.io')(server);
Update
I think this could be a port error, try to open the required port or check if something blocks it.
I made a little app to test Socket.IO, you can see the connection changes in the browser's console.
Live example

How to create a nodejs app that keeps listening to ports and does not exist

I need a skeleton of NodeJS app that listens to a port and does not exit.
Normally when you execute a JS file, it exits after finishing executing. I think a while(true) {} is the wrong way to go.
Can you provide some code sample for non-exiting JS code? It is a little bit like NodeJS web server, but I don't know how to do this.
Use the built-in http library:
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
After establishing a listener, unless an exception is thrown, execution will continue as the event loop waits for a message to be received.
You get much the same behavior if you were to do something with setInterval(). Since NodeJS knows there is an interval or pending action, it will continue execution until stopped or an exception is thrown.

What keeps event loop open when listening for I/O events?

Node.js's website says that the framework "exits the event loop when there are no more callbacks to perform."
What I haven't found clearly explained anywhere is what keeps the event loop running once you initiate an I/O module that is waiting for input. For example, in this canonical "Hello World" HTTP server example, Node.js continues listening indefinitely for incoming HTTP requests:
require('http').createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(8080);
While there is always the potential for a callback to the implicit request event handler, until an actual HTTP request comes in, there's no event being handled. Does this mean that the statement from the Node.js website isn't strictly true? Or is there some nuance here that I am missing?
The nuance is that there are callbacks "under the hood" as well.
In this case, the HTTP server is waiting for incoming connections on a TCP port, and until that port is explicitly closed (server.close()), this adds to the list of pending callbacks.
You don't even have to define a request handler to demonstrate this:
require('http').createServer().listen(8080);
And this shows what happens when you close the port after a few seconds:
var server = require('http').createServer().listen(8080);
setTimeout(function() {
server.close();
}, 2000);

node.js http request/response parameters

I'm still somewhat confused by how node callbacks work. Looking at this tutorial: http://www.nodebeginner.org/
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
My understanding is that the request and response parameters are passed when the server receives a request. However, I'm not sure how you would tell by the syntax. Does the createServer function not return anything until it actually receives a request, upon which it returns two objects, the request and the response?
No, the createServer method returns immediately, with a new web server object. That web server object's listen method is then immediately called, and the server begins listening for connections on port 8888. The listen call returns immediately as well; you can demonstrate this by adding a console.log('here'); on the next line and seeing how it writes to the terminal as soon as you run the script. As a result of the listen call, any time a new HTTP request is made to port 8888, the callback which was the sole argument to createServer is called to handle the request.
Since Node runs in a single thread (more or less), any operation that would block that thread--like waiting around for a server connection, or a database query, or a response to a remote request--is handled asynchronously, through the use of callbacks like the one in your example.

Accessing http object in a Node.js module

OK, can someone tell me what's going on? I have this in my main file:
var http = require('http').createServer(function (req,resp){
console.log("Started");
});
http.listen(1337);
I start the server and console.log doesn't log anything. I load a webpage, and every time I load it, I get the console.log("Started") message. What gives?
The console.log() is run inside the HTTP request listener function, which only runs when the HTTP server receives a request. When you create the server, the listener function isn't invoked, so console.log() doesn't run.
If you want the message to run on HTTP server listen, use it in the listen() function's callback.
server.listen(80, function() {
// this runs when the server has been started
});

Resources