← Back to Tutorials Chapter 1

Getting Started with Node.js

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript on the server side, enabling you to build fast, scalable network applications.

Key Benefit: Node.js uses non-blocking, event-driven I/O, making it lightweight and efficient for data-intensive real-time applications.

Why Choose Node.js?

System Requirements

Node.js vs Browser JavaScript

AspectBrowserNode.js
Global Objectwindowglobal
DOM/BOMAvailableNot available
Module SystemES Modules (import/export)CommonJS + ES Modules
File SystemNo accessFull access (fs module)
RuntimeSandboxedFull system access

Command Line Basics

Node.js is primarily used through the command line. Here are essential commands:

# Check Node.js version
node --version

# Run a JavaScript file
node app.js

# Start REPL (interactive shell)
node

# Run with inspector for debugging
node --inspect app.js

# Execute a one-liner
node -e "console.log('Hello, Node!')"

The V8 Engine

V8 is Google's open-source high-performance JavaScript engine, written in C++. It compiles JavaScript directly to native machine code using JIT (Just-In-Time) compilation. Node.js embeds V8 to execute JavaScript on the server.

Node.js architecture showing V8, libuv, and Event Loop layers

Node.js Architecture

Node.js consists of three main layers:

  1. JavaScript (V8): Handles your application code and core JS execution.
  2. Node API (libuv): Provides asynchronous I/O operations like file system, networking, and concurrency.
  3. Event Loop: Coordinates callbacks and ensures non-blocking execution.

The Event Loop

The event loop is what allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. It works by offloading operations to the system kernel whenever possible.

Event loop phases: timers, I/O callbacks, idle, poll, check, close

The event loop has several phases:

Tip: Understanding the event loop is crucial for writing performant Node.js applications. Always avoid blocking the event loop with synchronous operations.

Prerequisites

Before diving deeper, ensure you have:

Your First Node.js Application

Create a file named hello.js and add:

// hello.js
console.log("Hello, Node.js!");

// Access process info
console.log("Node version:", process.version);
console.log("Platform:", process.platform);
console.log("Current directory:", process.cwd());

Run it with: node hello.js

Exercise: Create a Node.js script that prints your name, the current date and time, and the operating system platform. Run it from the terminal.