Executing code before libUV initializing in node.js

Viewed 4

I read the different articles including official node.js documentation. And I still don't understand sequence of executing the following code:

console.log('start');
setTimeout(() => console.log('macrotask'));
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick 1'));
Promise.resolve().then(() => console.log('microtask 1'));
Promise.resolve().then(() => console.log('microtask 2'));
console.log('end');

/// outputs:
///
/// start
/// end
/// nextTick 1
/// microtask 1
/// microtask 2
/// macrotask
/// immediate

I read about difference between setTimeout and setImmediate:

The order in which the timers are executed will vary depending on the context in which they are called. If both are called from within the main module, then timing will be bound by the performance of the process (which can be impacted by other applications running on the machine).

After that I understood that node.js event-loop works when it is running, because if it would be in event-loop you saw another behaviour:

setTimeout(() => {
  console.log('start');
  setTimeout(() => console.log('macrotask'));
  setImmediate(() => console.log('immediate'));
  process.nextTick(() => console.log('nextTick 1'));
  Promise.resolve().then(() => console.log('microtask 1'));
  Promise.resolve().then(() => console.log('microtask 2'));
  console.log('end');
});

/// outputs:
///
/// start
/// end
/// nextTick 1
/// microtask 1
/// microtask 2
/// immediate
/// macrotask

So executing of node.js programm divides at "until event-loop" and "in event-loop". Right?

I would like to know when the node.js programm enters into event-loop of node.js (runs libUV)?

What does it mean "main module" (can nextTick be invoked in the "main module"?)?

P.S Sorry for that amount of questions, but they all are interconnected

0 Answers
Related