DEVELOPER SANDBOX Academy of Mastery
WelcomeBuild · Explore · Create SD
REFERENCE GUIDE

Node.js Reference Guide

Node.js setup, commands, modules, tooling, and macOS implementation reference.

Jump to:

Node.js at a Glance

Node.js runs JavaScript outside the browser using the V8 engine. It is commonly used for servers, APIs, command-line tools, build tooling, automation, real-time applications, and backend services.

macOS default recommendation: install an LTS Node version through a version manager such as nvm. For production work, stay on an Active or Maintenance LTS line unless a project explicitly requires Current.

Node vs Browser

Node has JavaScript, timers, promises, URL, streams and many Web APIs, but it does not provide browser DOM globals such as document or window.

Node / npm / npx

node runs JavaScript. npm manages packages and project scripts. npx/npm exec runs package-provided command-line tools.

Production Version

As of 2026-08-31: Node 24.20.0 is LTS; Node 26.8.1 is Current. Prefer LTS for ordinary production work.

Project Files

package.json describes the package; package-lock.json locks resolved dependencies; node_modules/ holds installed packages; .nvmrc can pin the project Node version.

Modern Module Default

For new application code, use explicit ESM with "type": "module" and import/export. Keep CommonJS when compatibility requires it.

Fast Dev Loop

nvm use → npm install → node --watch src/app.js → node --test. Put repeatable commands in package.json scripts.

macOS Installation & Version Management

Use one primary installation strategy. Mixing a system installer, Homebrew Node, and a version manager can make which node point to the wrong binary.

The three columns below read as Use / Install / Notes.

nvm — Recommended

Use: best for developers who need to switch Node versions per project. npm's own documentation strongly recommends a Node version manager.

Install:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.6/install.sh | bash
source ~/.zshrc
command -v nvm
nvm install 24
nvm use 24
node -v
npm -v

Notes: macOS uses zsh by default. If ~/.zshrc does not exist, create it with touch ~/.zshrc, then rerun the installer or add the nvm load lines manually.

Official Node Installer

Use: simple single-version setup when you cannot or do not want to use a version manager.

Download: nodejs.org/en/download

Select the LTS release for normal development. Run the macOS installer, then verify:

node -v
npm -v
which node

Notes: npm documentation prefers a version manager because installer-based global packages can lead to permissions problems. Do not use sudo npm install -g as a routine fix.

Homebrew

Use: convenient when you deliberately manage Node through Homebrew rather than nvm.

LTS 24:

brew install node@24
brew info node@24

The unversioned formula currently tracks Node 26:

brew install node

Notes: node@24 is keg-only. Follow Homebrew's displayed PATH instructions if the executable is not found. For projects needing several Node lines, nvm is usually simpler.

Version & nvm Commands

Use these when setting up a Mac, switching projects, or checking which Node binary is active.

Verify Node and npm
Verify nvm
Install Node 24 LTS
List installed versions
List remote LTS versions
Switch Node version
Set the default
Pin a project with .nvmrc
Find the selected binary

Start a Node Project

Left side shows the action; right side shows the implementation or resulting project structure.

1. Create and initialize

Create a clean project directory and a package.json.

mkdir my-node-app
cd my-node-app
git init
npm init -y
2. Pin Node

Add a project Node version file.

echo "24" > .nvmrc
nvm use
3. Use explicit ESM

For a new ESM project, add this to package.json.

{
  "type": "module"
}
4. Add scripts

Put repeatable tasks behind project scripts.

{
  "scripts": {
    "start": "node src/app.js",
    "dev": "node --watch src/app.js",
    "test": "node --test"
  }
}
5. Basic folders

A small service does not need a complex architecture.

my-node-app/
├── src/
│   ├── app.js
│   ├── routes/
│   └── services/
├── test/
├── .env
├── .gitignore
├── .nvmrc
├── package.json
└── package-lock.json
6. Ignore local/generated files

Do not commit dependencies, secrets, logs, or OS metadata.

node_modules/
.env
*.log
.DS_Store
coverage/

package.json Quick Reference

package.json is the project manifest. Node uses some fields directly; npm uses many additional fields.

name / version / private

name identifies the package; version follows semantic versioning. For an application that should never be published accidentally, use "private": true.

type

"type": "module" makes nearby .js files ESM. "type": "commonjs" makes them CommonJS. Be explicit.

scripts

Named development commands run with npm run <name>. start and test also have npm shorthand commands.

dependencies

Packages required when the application runs.

devDependencies

Development-only tools such as linters, test helpers, build tools, or TypeScript tooling.

engines

Declare the Node versions the package expects. Enforcement depends on package-manager settings and environment.

main vs exports

main is the older single entry point. For packages, Node recommends modern exports for a deliberate public interface and subpath control.

Essential Node Commands

These are runtime commands from the Node executable itself.

Run a file
Interactive REPL
Evaluate one expression
Print an expression
Syntax check only
Watch mode
Watch selected paths
Load .env
Optional .env
Run tests
Open the inspector
Break on first line
Run a package script natively
Help

npm / npx Essentials

npm ships with standard Node installations and handles dependencies and project scripts. This section contains the Node-adjacent commands you reach for most often.

Initialize package.json
Install project dependencies
Add runtime dependency
Add development dependency
Remove dependency
Run project script
Pass arguments to a script
Run package binary
Clean reproducible install
See outdated packages
Update allowed versions
Audit dependencies
Inspect installed tree
Package metadata
npm help

Modern Modules: ESM & CommonJS

Node supports both module systems. For new code, explicit ESM is usually the clearest choice. Keep CommonJS where compatibility requires it.

ESM — import / export

Enable with "type": "module", use .mjs, or another explicit ESM marker.

// math.js
export function add(a, b) {
  return a + b;
}

// app.js
import { add } from './math.js';
console.log(add(2, 3));
CommonJS — require

Use .cjs or "type": "commonjs" when you need CommonJS explicitly.

// math.cjs
exports.add = (a, b) => a + b;

// app.cjs
const { add } = require('./math.cjs');
Built-in modules

Use the node: prefix to make it obvious an import is a Node built-in rather than an npm package.

import { readFile } from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';
ESM file paths

On Node 24, import.meta.dirname and import.meta.filename are stable for local file modules.

console.log(import.meta.dirname);
console.log(import.meta.filename);

const file = new URL('./data.json', import.meta.url);
Dynamic import

Load a module only when needed. import() works in both ESM and CommonJS.

const module = await import('./feature.js');
module.run();
JSON modules

Modern ESM imports JSON with an import attribute.

import config from './config.json' with { type: 'json' };

Core APIs You Reach for Often

Node includes a large standard library. Prefer a built-in API when it cleanly solves the problem; add a package when the ecosystem library provides meaningful value.

File system — promises
Path
Process
URL
Crypto
Buffer
Events
Streams
Native fetch

HTTP & API Implementation

Node can serve HTTP without a framework. A framework such as Express or Fastify becomes useful when routing, middleware, validation, plugins, or application structure justify the dependency.

Minimal HTTP server
JSON response
Route by method and pathname
Fetch JSON
POST JSON with fetch
Request timeout
Graceful server shutdown

Environment, Arguments & Process

Keep machine-specific configuration outside source code. Do not commit secrets in .env.

Create .env
Load .env at startup
Read environment values
Command-line arguments
Current working directory
Exit status

Testing, Watch & Debugging

Node includes a test runner and inspector, so a small project can begin testing and debugging without adding a framework.

Built-in test example
Run discovered tests
Watch tests
Debug with inspector
Break before execution
Timing a code path
Trace warnings

Node 24 + TypeScript

Node 24 can execute TypeScript containing erasable type syntax through built-in type stripping. This is useful for lightweight scripts, but it is not a replacement for TypeScript type checking.

Run erasable TypeScript

On current Node 24 LTS, type stripping is stable. Inline types are removed at runtime.

// script.ts
const name: string = 'Node';
console.log(name);

// run
node script.ts
What Node does NOT do

Node's built-in type stripping does not type-check and does not read tsconfig.json.

# still type-check separately
npx tsc --noEmit
Full TypeScript runtime support

For features needing transformation or full tsconfig-aware tooling, use a tool such as tsx.

npm install -D tsx
npx tsx src/app.ts
# or
node --import=tsx src/app.ts
Type imports

When using built-in stripping, use the type keyword for imports that exist only to the type system.

import type { User } from './types.ts';
import { save, type SaveOptions } from './save.ts';
Important limitation

Syntax requiring JavaScript generation—such as some enums, runtime namespaces, and parameter properties—requires transformation rather than simple stripping.

// use full TypeScript tooling when transformed syntax is required

Best Implementation Patterns

These patterns keep Node projects easier to upgrade, debug, deploy, and hand to another developer.

Use an LTS line for production
Be explicit about module format
Commit the lockfile
Keep dependencies local
Prefer async I/O in servers
Use built-ins before adding trivial dependencies
Validate configuration at startup
Handle async errors at boundaries
Separate responsibilities
Graceful shutdown
Security maintenance

Troubleshooting Fast Map

Check the active runtime and project state before reinstalling everything.

node: command not found

Run command -v nvm, which node, and reopen/source your shell config. For nvm on macOS, check ~/.zshrc.

Wrong Node version

Run nvm ls, nvm use, which node, and node -p "process.execPath". A Homebrew or installer binary may be earlier on PATH.

Cannot use import

Add "type": "module", use .mjs, or convert the file to CommonJS. Do not mix module systems accidentally.

require is not defined

The file is running as ESM. Replace require() with import, use .cjs, or deliberately bridge with createRequire().

ERR_MODULE_NOT_FOUND

Check the package is installed, relative ESM imports include the actual file path/extension, and spelling/case matches the filesystem.

EADDRINUSE

Another process already owns the port. On macOS use lsof -i :3000, identify the process, then stop the correct process.

npm EACCES / permission errors

Prefer a version manager so user-owned Node/npm directories are used. Avoid making sudo npm install -g your normal workflow.

Dependencies seem corrupted

For a lockfile-driven clean rebuild: remove node_modules and run npm ci. Do not delete the lockfile unless you intentionally want dependency resolution to change.

Apple Silicon mismatch

Check uname -m, node -p "process.arch", and file "$(which node)". Prefer native arm64 packages on Apple Silicon.

Unexpected working path

process.cwd() follows where the command was launched. Use import.meta.dirname when you mean the current ESM module directory.

Common Workflow Recipes

Short repeatable sequences for the situations you encounter most often.

New project

Create, pin, initialize, and start.

mkdir app && cd app
nvm use 24
npm init -y
mkdir src
touch src/app.js
node src/app.js
Clone existing project

Use the project's Node version and lockfile.

git clone <repo>
cd <repo>
nvm use
npm ci
npm test
npm run dev
Daily development

Run a repeatable dev script rather than remembering long commands.

npm run dev
# usually maps to:
node --watch src/app.js
Before commit

Run the project's checks locally.

npm test
npm run lint --if-present
npm audit
Upgrade Node major

Change runtime deliberately, reinstall, then test.

nvm install 24
nvm use 24
node -v
npm ci
npm test
Find runtime facts

Fast diagnosis for platform and binary mismatches.

node -p "process.version"
node -p "process.platform"
node -p "process.arch"
node -p "process.execPath"
npm -v

Official Documentation & Downloads

Prefer the official Node/npm documentation for runtime behavior and command syntax. Use the nvm repository for nvm-specific commands.

Node.js Download

LTS and Current installers/binaries.

Node.js Releases

Release status, LTS lifecycle, and supported lines.

Node 24 LTS API Index

API documentation pinned to the Node 24 LTS line.

Command-line API

Runtime flags such as --watch, --test, --env-file, and --inspect.

ECMAScript Modules

ESM loading, import/export, import.meta, JSON modules, interoperability.

Packages

package.json module fields, type, exports, imports, package entry points.

TypeScript in Node

Built-in type stripping and its limits.

File System

fs and fs/promises APIs.

HTTP

Built-in HTTP server/client primitives.

Process

process.env, argv, cwd, platform, exit behavior.

Test Runner

node:test and command-line test runner.

Globals

fetch, AbortController, and other global APIs.

npm Documentation

Package manager documentation and CLI reference.

Install Node and npm

npm's setup recommendations, including version managers.

npm init

Create package.json and initialize workspaces/packages.

npm install

Dependency installation and dependency classifications.

npm run

Run package scripts and pass arguments.

nvm

Node Version Manager installation and commands for macOS/Linux.

Homebrew node@24

Homebrew's versioned Node 24 LTS formula.