Node.js is an open-source, cross-platform runtime that executes JavaScript outside the browser by embedding the V8 engine inside a C++ layer. It provides a complete stack—runtime, interpreter, and native bindings—so you can build network services, CLI tools, and full-stack applications using a single language.
Why Use Node.js Instead of Just the Browser?
JavaScript is an interpreted language: every .js file must be parsed and executde by an engine. In the browser, that engine is V8 (Chrome), SpiderMonkey (Firefox), or JavaScriptCore (Safari). When you move to server-side or build tooling, you need the same engine available on the host OS. Node.js fills that gap, acting as a portable "mini server" that:
- Bootstraps your build pipeline (Webpack, Vite, Rollup).
- Serves APIs with minimal overhead.
- Runs scripts for CI/CD, data migrations, or cron jobs.
Installation & Version Switching
Download the LTS installer from nodejs.org or use a version manager:
# Install via nvm (macOS/Linux)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install --lts
nvm use --lts
# Verify
node -v # e.g., v20.12.2
npm -v # e.g., 10.5.0
Module Resolution Walk-through
When require('something') is encountered, Node.js searches in the following order:
- Core modules such as
fs,http,crypto. - Relative files (
./foo.js,../lib/bar.json). - Folder modules (
./myLib/) that contain anindex.jsor apackage.json#mainentry. - node_modules walking upward from the current directory to the filesystem root.
Example project structure:
project/
├── src/
│ └── app.js
├── utils/
│ └── helper.js
├── node_modules/
│ └── lodash/
└── package.json
Package Management & Mirrors
npm ships with Node.js, but its default registry can be slow in some regions. Switch to a mirror:
# One-off install via Taobao mirror
npm install lodash --registry=https://registry.npmmirror.com
# Permanent alias
npm config set registry https://registry.npmmirror.com
Install project dependencies:
npm init -y
npm install express dotenv helmet
REPL: Instant Feedback Loop
Launch the enteractive shell to test snippets:
$ node
> const crypto = require('crypto');
> crypto.randomBytes(16).toString('hex');
'9f8e5b2c...'
> .exit
Common CLI Recipes
| Task | Command |
|---|---|
| Show installed version | node -v |
| List global packages | npm ls -g --depth=0 |
| Pin Node version in project | nvm use 18.19 && node -v > .nvmrc |
| Clean cache | npm cache clean --force |
Minimal HTTP Server with Express
// server.js
import express from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (_req, res) => res.json({ uptime: process.uptime() }));
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
Run with:
node server.js
# or
npx nodemon server.js