Are the codes written in index.js executed before event-loop?

Asked 2 years ago, Updated 2 years ago, 38 views

For example, if I write a single line of code in index.js called console.log("Hello"); and type node index.js in Terminal 1) Load global module (timer, console...) and so on) 2) Execute the code in index.js 3) While rotating the event-loop, take and execute the callback functions in the event-queue one by one.

Is this the right order?

node.js

2022-09-22 21:14

1 Answers

The order is correct.

https://developer.mozilla.org/ko/docs/Web/JavaScript/EventLoop

The event queue is a data structure that contains a handler (function) that implements logic generated by a specific asynchronous event, and in the case of questioning, there is no entry into the event queue, so there will be no actual import and execution.

(Additional) You didn't answer the original question ;;

You have to do something at the entry point of the code, index.js, to enter the event queue, and the event loop is a structure that runs after checking if there is work in the queue, so the entry point code will always run first.

Besides, the code at the entry point would have entered the Colstack first and piled up... The event loop checks if the call stack is empty and runs the oldest task in the event queue when it is not, and since the main is single thread, the task in the event queue is not expected to run first.

There's a famous phrase that holds Node.js' principles of action well.

In Node.js everything runs in parallel, except your code.

In Node.js, everything works in parallel. Except for your code

The actual Node.js processing of the task is: CPU-bound and I/O-bound methods exist. I/O-bound refers to tasks such as networking, file system, DB access, and so on that need to wait for completion in the main thread. In fact, Node.js processes Operation on the Call Stack without waiting for the main thread to complete the I/O. When I/O is complete, the callback enters the event queue, and if there is no work on the Call Stack, take it out one by one and run it.

Although this is called a single thread, (Strictly speaking. Or maybe not...) It's a way of digesting multiple tasks without blocking. (Synchronous Programming)

Based on @Rebero's explanation,

If I can explain these additionally, I think it will be a good answer to how Node.js works.

Although it is English, is helpful in the picture.

This is the first post I heard about Node.js structure.


2022-09-22 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.