0% found this document useful (0 votes)
8 views

NodeJS Overview

Node.js is a JavaScript runtime that allows JavaScript to run on the server-side. It uses an event-driven, non-blocking I/O model that makes it suitable for data-intensive real-time applications. The document discusses Node.js basics, its event-driven architecture, the event loop, and provides code examples of synchronous, asynchronous, promises, and async/await code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

NodeJS Overview

Node.js is a JavaScript runtime that allows JavaScript to run on the server-side. It uses an event-driven, non-blocking I/O model that makes it suitable for data-intensive real-time applications. The document discusses Node.js basics, its event-driven architecture, the event loop, and provides code examples of synchronous, asynchronous, promises, and async/await code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

NodeJS Overview

Node.js Basics Introduction


Node.js Overview

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.

It allows you to run JavaScript on the server-side, enabling full-stack


development with a single language.

It's known for its non-blocking, event-driven architecture, which makes it


suitable for building scalable network applications.

Key Components of a Simple Node.js Application

1. Server: The core component that handles incoming requests and sends
responses.

2. Request: Represents the incoming client request, containing data such as


URL, headers, and payload.

3. Response: Represents the server's response to the client, including status


code, headers, and the response body.

Event-Driven Architecture
Event-Driven Programming

Node.js uses an event-driven, non-blocking I/O model.

In this model, operations are handled asynchronously, allowing the server to


handle multiple requests concurrently without waiting for any single operation
to complete.

Components of Event-Driven Architecture

1. Events: Signals that something has happened, like a request or a timer.

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.

It continuously checks the event queue and processes events, allowing


Node.js to perform asynchronous operations.

Phases of the Event Loop

1. Timers: Executes callbacks scheduled by setTimeout and setInterval .

2. Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.

3. Idle, Prepare: Internal use, typically ignored.

4. Poll: Retrieves new I/O events, executing their callbacks.

5. Check: Executes callbacks from setImmediate .

6. Close Callbacks: Executes close event callbacks, e.g., when a socket or


handle is closed.

Event Loop Execution Flow

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.

This cycle continues as long as there are events to process.

Here's an image to help visualize the event loop:

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 .

Asynchronous Code Example

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');

This example uses Promises to handle asynchronous file reading, providing a


cleaner syntax compared to callbacks.

Async/Await Example

NodeJS Overview 4
javascriptCopy code
const fs = require('fs').promises;

async function readFile() {


try {
const data = await fs.readFile('/path/to/file', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}

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.

Visualizing the Event Loop


Here's an image to help visualize the event loop:
By understanding these basics and practicing with the code snippets, you'll be
well-prepared to build and manage efficient Node.js applications and handle
interview questions on the topic.

Code Snippets to Understand Web API, Micro Task Queue, and


Callback Queue
1. Synchronous Code Example

NodeJS Overview 5
console.log('Synchronous 1');

console.log('Synchronous 2');

This code executes synchronously, with each line running in order without
delay.

2. setTimeout (Callback Queue) Example

console.log('Start');

setTimeout(() => {
console.log('Callback from setTimeout'); // This will be lo
gged last
}, 0);

console.log('End');

The setTimeout function schedules the callback to be placed in the callback


queue after the specified delay (0 ms in this case). It will execute after all
synchronous code is finished.

3. Promises (Micro Task Queue) Example

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');
});

Expected Output Order:

1. Synchronous 1

2. Synchronous 2

3. Promise 1

4. Promise 2

5. setTimeout 1

6. setTimeout 2

Explanation:

The synchronous code ( console.log ) runs first.

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.

Visual Representation of Event Loop Phases

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

You might also like