Affiliate link

Node.js - Introduction

Node.js is a JavaScript runtime that runs on Chrome's V8 JavaScript engine. It is open-source and cross-platform (Windows, Linux, MacOS, etc.).

Node.js application runs in a single process and provides asynchronouse I/O that achieves non-blocking behaviour. Node.js is primarily used for non-blocking, event-driven servers such as web application server.

Non-blocking

Node.js achieves non-blocking I/O through its event-driven, asynchronous architecture.

In traditional web servers, each client request would be handled by a separate thread, which could lead to resource contention and blocking I/O operations, especially in high-traffic applications. In contrast, Node.js uses a single thread and an event loop to handle incoming requests.

When a client request is received, Node.js creates an event and passes it to the event loop. The event loop then checks the event queue to see if any handlers are registered for that type of event. If there is a registered handler, it is invoked to process the event. The handler may include asynchronous I/O operations, such as reading from a file or making an HTTP request.

Instead of blocking the event loop while waiting for I/O operations to complete, Node.js continues to process other events in the queue. When the I/O operation completes, a new event is added to the event queue, and the event loop processes it as before.

This approach allows Node.js to handle many client requests simultaneously, without blocking the event loop or consuming too many resources. As a result, Node.js can achieve high levels of concurrency and scalability, making it well-suited for building high-performance, real-time applications.

Node.js - Benefits

Node.js - Example HTTP server

const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
    res.statusCode = 200
    res.setHeader('Content-Type', 'text/plain')
    res.end('Hello, LearnCodeNow!\n')
})

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}`)
})
Affiliate link
Affiliate link
Advertisment
StudioPress
Fiverr
Ad - SiteGround WooCommerce hosting - best home for your online store. Fast WooCommerce, Free SSL, Top support. Learn more.