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.
var fs = require("fs");
var ws = fs.createWriteStream("C:\\test.txt");
ws.on("open", function(fd) {
console.log("#Event file 'open'");
});
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) {}
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var CustomEventEmitter = function() {};
util.inherits(CustomEventEmitter, EventEmitter);
var customInstance = new CustomEventEmitter();
customInstance.on("tick", function() {
console.log("#Event custom 'tick'");
});
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.
, , ?
, :)