NodeJS Overview
NodeJS Overview
1. Server: The core component that handles incoming requests and sends
responses.
Event-Driven Architecture
Event-Driven Programming
2. Event Emitters: Objects that emit named events, and listeners can listen for
those events.
3. Event Listeners: Functions that are called when a specific event is emitted.
NodeJS Overview 1
The Event Loop
Event Loop Overview
The event loop is the heart of Node.js, enabling non-blocking I/O operations.
2. Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.
The event loop checks the queue for events and processes them in the order
of their arrival.
It handles each phase sequentially, moving to the next phase once the current
one is complete.
NodeJS Overview 2
Example Code Snippets
Synchronous Code Example
javascriptCopy code
const fs = require('fs');
try {
const data = fs.readFileSync('/path/to/file', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
console.log('This will log after the file read operation');
This code reads a file synchronously, blocking the execution of the code until
the file is read. It uses fs.readFileSync .
javascriptCopy code
const fs = require('fs');
NodeJS Overview 3
fs.readFile('/path/to/file', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
console.log('This will log before the file read operation com
pletes');
This code reads a file asynchronously using a callback function, allowing the
rest of the code to execute while waiting for the file read operation to
complete.
Promises Example
javascriptCopy code
const fs = require('fs').promises;
fs.readFile('/path/to/file', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
console.log('This will log before the file read operation com
pletes');
Async/Await Example
NodeJS Overview 4
javascriptCopy code
const fs = require('fs').promises;
readFile();
console.log('This will log before the file read operation com
pletes');
This code uses async / await for asynchronous file reading, making it look
similar to synchronous code while still being non-blocking.
NodeJS Overview 5
console.log('Synchronous 1');
console.log('Synchronous 2');
This code executes synchronously, with each line running in order without
delay.
console.log('Start');
setTimeout(() => {
console.log('Callback from setTimeout'); // This will be lo
gged last
}, 0);
console.log('End');
console.log('Start');
Promise.resolve().then(() => {
console.log('Promise resolved'); // This will be logged bef
ore the setTimeout callback
});
console.log('End');
Promises use the micro task queue, which has higher priority than the callback
queue. The promise resolution will execute after the synchronous code but
before any setTimeout callbacks, even if the delay is 0 ms.
NodeJS Overview 6
Combined Example
To see how these different mechanisms interact, here’s a combined example:
console.log('Synchronous 1');
setTimeout(() => {
console.log('setTimeout 1');
}, 0);
Promise.resolve().then(() => {
console.log('Promise 1');
});
console.log('Synchronous 2');
setTimeout(() => {
console.log('setTimeout 2');
}, 0);
Promise.resolve().then(() => {
console.log('Promise 2');
});
1. Synchronous 1
2. Synchronous 2
3. Promise 1
4. Promise 2
5. setTimeout 1
6. setTimeout 2
Explanation:
NodeJS Overview 7
The setTimeout callbacks are scheduled to run after 0 ms, but they go into the
callback queue.
The Promises are resolved and their callbacks go into the micro task queue.
The micro task queue is processed before the callback queue, so the Promise
callbacks run before the setTimeout callbacks.
This diagram helps visualize the event loop, illustrating how synchronous code,
promises, and setTimeout callbacks are processed in Node.js. Understanding this
flow is crucial for mastering asynchronous programming in Node.js.
NodeJS Overview 8