Node.js
Summary
- Node.js, created by Ryan Dahl in 2009, is a JavaScript runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server, enabling full-stack development with a single language.
- Cross-Platform: Runs on Windows, macOS, and Linux.
- Open Source: Maintained by the OpenJS Foundation.
- Event-Driven & Asynchronous I/O: Employs a non-blocking architecture, making it highly efficient for scalable applications. For example, instead of waiting for a file to be read, Node.js can continue executing other code.
- REPL: Includes a "Read-Evaluate-Print-Loop" for interactive code testing.
- Global Objects: Provides a
globalobject, similar to the browser'swindow. For cross-environment compatibility, it's best to useglobalThis.
Key Features:
Code Example
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});Modules & Ecosystem
- Node.js uses a module system to encapsulate code, preventing variables from polluting the global scope.
- This is achieved by wrapping each module's code in an Immediately Invoked Function Expression (IIFE).
- CommonJS (CJS): The original, synchronous module system in Node.js.
- Importing:
const myModule = require('./myModule'); - Exporting:
module.exports = { myFunction }; - ES Modules (ESM): The modern, asynchronous standard.
- Importing:
import { myFunction } from './myModule.js'; - Exporting:
export { myFunction }; - You can define the module type in
package.jsonwith the"type": "module"field for ESM. - JavaScript is single-threaded, using a call stack to execute code synchronously.
- Node.js handles long-running tasks (like file I/O or network requests) without blocking the main thread using Libuv, a C library that manages an event loop and a thread pool.
- When an asynchronous operation like
fs.readFile()is called, Node.js offloads the task to Libuv. - The main thread continues to execute other code.
- Once the task is complete, its callback function is placed in a queue.
- The event loop picks up the callback from the queue and pushes it to the call stack for execution.
- This non-blocking model makes Node.js highly performant. Avoid synchronous methods like
fs.readFileSync()in server environments as they block the entire application.
Understanding Modules in Node.js
Module Patterns: CommonJS vs. ES Modules
The Asynchronous Nature of Node.js
Runtime Engine
- compiler to execute JavaScript efficiently through a multi-stage process:
- 1. Lexical Analysis: The engine first breaks down the code into a series of "tokens," which are the smallest units of meaning in the code.
- 2. Syntax Analysis: These tokens are then assembled into an Abstract Syntax Tree (AST), a hierarchical structure representing the code's syntax.
- 3. Interpreter (Ignition): The AST is passed to the Ignition interpreter, which quickly generates and executes bytecode. During this phase, Ignition gathers profiling data to identify "hot" functions—code that is executed frequently.
- 4. Compiler (TurboFan): For these hot functions, the TurboFan optimizing compiler generates highly optimized machine code. If its assumptions about the code prove incorrect, TurboFan can "de-optimize" and fall back to the bytecode, ensuring correctness. This sophisticated process combines the fast startup of an interpreter with the high performance of a compiler, making Node.js both quick and efficient.
How the V8 Engine Works
V8, Google's open-source JavaScript engine written in C++, is the powerhouse behind Node.js. It uses a **Just-In-Time (JIT)*What's New
- Node.js 22, released in April 2024, introduces several new features, including updates to the V8 JavaScript engine, improved support for ES modules, and various performance enhancements to boost application speed and reliability.
Official Resources