Skip to main content

Node JS

General aspects of Node JS, differences with browser JavaScript, and server-side usage.

What is Node JS?

Node.js is a JavaScript runtime environment built on Chrome's V8 engine. It allows executing JavaScript code on the server side, outside the browser. It was created by Ryan Dahl in 2009 with the goal of creating highly scalable and efficient applications for handling I/O (Input/Output) operations.

Key Features

  • Asynchronous and non-blocking: Node uses asynchronous operations by default, making it ideal for applications that handle many concurrent requests.
  • Single-threaded: Although single-threaded, it handles concurrency through the Event Loop and delegates I/O operations to OS system threads using libuv.
  • Vast Ecosystem: Powered by npm, the largest open-source package ecosystem.

Difference with Browser JavaScript

  • In the browser, JavaScript runs within the context of the DOM.
  • In Node.js, there is no DOM; native modules like fs or http are used to access the file system or build web servers.

How can Node JS be concurrent?

Node.js is single-threaded, but handles concurrency using:

  • Event Loop: Manages and dispatches asynchronous tasks.
  • libuv: C library providing a thread pool to execute blocking tasks (such as disk or network access) in a non-blocking manner for the main thread.

Example:

const fs = require('fs');

console.log('Start');

fs.readFile('file.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log('Content:', data);
});

console.log('End');

Event Loop

The Event Loop is the mechanism allowing Node.js to execute non-blocking operations despite being single-threaded.

Event Loop Phases (Simplified):

  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 Node use only.
  4. Poll: Retrieves new I/O events.
  5. Check: Executes setImmediate() callbacks.
  6. Close callbacks: E.g., socket.on('close').

Microtasks vs Macrotasks

  • Microtasks: Promises (Promise.then), queueMicrotask.
  • Macrotasks: setTimeout, setInterval, setImmediate.

Native Modules in Node JS

  • fs module: File system interaction (readFile, writeFile).
  • http module: Low-level HTTP server creation.
  • path module: Normalizes and builds directory file paths (path.join).
  • os module: Provides OS system details (os.platform(), os.cpus()).

Self-Assessment Quiz

Cargando cuestionario...