I am familiar with event-based systems in C ++, as well as with java. I tried to find out node.js and came up with interesting behavior, and I was hoping that someone could explain what was going on under the hood.
I have a program that looks like
var http = require("http"); function main(){ // Console will print the message console.log('Server running at http://127.0.0.1:8080/'); var server = 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'); }); server.listen(8080); //Why is this not blocking console.log('Main completed'); //main loop here prevents other stuff from working } main();
In languages ββlike java or c, I would expect two things. Or server.listen provides an event loop that causes server.listen to never return. Or server.listen creates a new thread and starts the event loop in the new thread, which returns immediately. Then it will call console.log, and then come back and close the program.
To test this, I also added a busy loop under the console .log that looks like.
var http = require("http"); function main(){ // Console will print the message console.log('Server running at http://127.0.0.1:8080/'); var server = 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'); }); server.listen(8080); //Why is this not blocking console.log('Main completed'); while(true){ console.log('hi'); } } main();
Server.listen returns immediately, and then loops into the busy cycle as expected. My browser cannot connect to the server, which is expected.
If I delete the busy cycle and return to the source code after console.log ("Main completed"); executed instead of starting the program, the main thread returns to the event loop.
How it works. Why does the main thread return to server code after the main thread returns?
Edit: I think re is allowed that the event queue does not exist in the main function, but where is it? What do they need it for? and when does the main function start with reference to it?