Introduction to Node.js

JavaScript everywhere. Run your code on servers, build tools, and command-line apps.

What Is Node

A JavaScript runtime built on Chrome's V8 engine — but without a browser.

// Browser JS vs Node.js:
//
// Browser:                    Node.js:
// ✓ DOM, window, document    ✗ No DOM, no window
// ✓ fetch, localStorage      ✓ File system, networking
// ✓ User interaction         ✓ Server-side processing
// ✗ No file system access    ✓ Full OS access
//
// Same language, different environment.

// What Node.js gives you:
// - Run JS files directly: node app.js
// - Access file system (read/write files)
// - Create HTTP servers
// - Build CLI tools
// - Access databases
// - Use OS-level APIs (processes, networking)

// Install: https://nodejs.org (LTS version)
// Verify:
// $ node --version    → v22.x.x
// $ npm --version     → 10.x.x

// Node.js is NOT a framework — it's a runtime.
// Express, Fastify, Hono = frameworks that run ON Node.js.

Running Code

Execute JavaScript files from the terminal.

// Create a file: hello.js
console.log("Hello from Node.js!");
console.log("Process ID:", process.pid);
console.log("Node version:", process.version);
console.log("Current directory:", process.cwd());

// Run it:
// $ node hello.js
// Hello from Node.js!
// Process ID: 12345
// Node version: v22.5.0
// Current directory: /Users/you/projects

// REPL (interactive mode):
// $ node
// > 2 + 2
// 4
// > "hello".toUpperCase()
// 'HELLO'
// > .exit

// Command-line arguments:
// greet.js:
const name = process.argv[2] || "World";
console.log("Hello, " + name + "!");

// $ node greet.js Alice
// Hello, Alice!

// Environment variables:
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || "development";
console.log("Running on port " + port + " in " + env);

// Exit codes:
// process.exit(0)  — success
// process.exit(1)  — error

Modules

Organize code into reusable files with import/export.

// ES Modules (modern — recommended):
// Add "type": "module" to package.json

// math.js:
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export const PI = 3.14159;

// app.js:
import { add, multiply, PI } from "./math.js";
console.log(add(2, 3));      // 5
console.log(multiply(4, 5)); // 20

// Default export:
// logger.js:
export default function log(msg) {
  console.log("[" + new Date().toISOString() + "] " + msg);
}

// app.js:
import log from "./logger.js";
log("Server started");

ES Modules use import/export syntax. Same as browser modules but running on the server.

1 / 2

File System

Read, write, and manipulate files and directories.

import fs from "node:fs/promises";
import path from "node:path";

// Read a file:
const content = await fs.readFile("data.txt", "utf-8");
console.log(content);

// Write a file:
await fs.writeFile("output.txt", "Hello, file system!");

// Append to file:
await fs.appendFile("log.txt", "New entry\n");

// Check if file exists:
try {
  await fs.access("config.json");
  console.log("File exists");
} catch {
  console.log("File not found");
}

// Read JSON:
const raw = await fs.readFile("package.json", "utf-8");
const pkg = JSON.parse(raw);
console.log(pkg.name, pkg.version);

// List directory:
const files = await fs.readdir("./src");
console.log(files); // ["app.js", "utils.js", ...]

// Create directory:
await fs.mkdir("./output", { recursive: true });

// Path utilities:
const fullPath = path.join(__dirname, "data", "file.txt");
const ext = path.extname("photo.jpg");   // ".jpg"
const base = path.basename("/a/b/c.txt"); // "c.txt"
const dir = path.dirname("/a/b/c.txt");   // "/a/b"

// Delete file:
await fs.unlink("temp.txt");

// Copy file:
await fs.copyFile("source.txt", "backup.txt");

HTTP Server

Create a web server in 10 lines of code.

import { createServer } from "node:http";

const server = createServer((req, res) => {
  // req = incoming request info
  // res = response we send back

  if (req.url === "/" && req.method === "GET") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Hello World</h1>");
  }
  else if (req.url === "/api/users" && req.method === "GET") {
    const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(users));
  }
  else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Not Found");
  }
});

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

// Test it:
// $ node server.js
// Open browser → http://localhost:3000
// Or: curl http://localhost:3000/api/users

// This is the foundation — frameworks like Express
// add routing, middleware, and convenience methods
// on top of this same http module.

FAQ

Common questions about Node.js.