Difference in node.js behavior. Event loop for inline and custom events.

I read about event loops in node.js. According to my reading of various articles and messages on stackexchange, I got that all callbacks are added at the end of the task queue, and after the main file is executed, all tasks in the queue are executed sequentially . I tried to confirm this with a small program. There I discovered strange behavior. Below is the contents of the main.js file that I created.

//Declare file open event handler
var fs = require("fs");
var ws = fs.createWriteStream("C:\\test.txt");
ws.on("open", function(fd) {
    console.log("#Event file 'open'");
});

//Wait for 5 seconds
var startTime = new Date().getTime();
console.log("Give time of 5 seconds to get file opened (being conservative)...\n");
while(new Date().getTime() - startTime < 5000) {}

//Create custom event
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var CustomEventEmitter = function() {};
util.inherits(CustomEventEmitter, EventEmitter);

//Declare custom event handler
var customInstance = new CustomEventEmitter();
customInstance.on("tick", function() {
    console.log("#Event custom 'tick'");
});

//Emit custom event
customInstance.emit("tick");

console.log("#End 'main.js'");

He gave me the following result:

Give time of 5 seconds to get file opened (being conservative)...

#Event custom 'tick'
#End 'main.js'
#Event file 'open'

The "#Event file" open "log is displayed after the" #End "main.js", but why the #Event custom "tick" log appeared first if it should have been in the task queue.

, , ?

, :)

+4
2

, emitter.emit() .

, :

  • fs.createWriteStream(), async, .

  • while , , .

  • tick. . emit() , : # 'tick'

  • . #End 'main.js'.

  • Node ( createWriteStream() . open, : #Event file ' open '

, .

+4

while, , CPU 5 . setInterval setTimeout. SetTimeout/Interval js- . 1 , , .

( - )

Javascript . , - , , .

, , . - CustomEventEmitter. jQuery click . , .

, - async , js-. while CustomEventEmitter , fs - .

, .

0

All Articles