Node.js Complete Guide: Download, Install & Getting Started
π Table of Contents
1. What is Node.js? 2. System Requirements 3. Download Options 4. Installation Guides 5. Getting Started 6. Working with Node.js 7. Development Tools 8. Troubleshooting 9. Additional Resources
π What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code outside of a web browser. It's built on Chrome's V8 JavaScript engine and uses an event-driven, non-blocking I/O model, making it efficient for building scalable network applications.
Key Features:
π₯οΈ System Requirements
Minimum Requirements:
Recommended for Development:
π₯ Download Options
Official Download Page:
Version Choices:
| Version Type | Description | Recommended For | |-------------|-------------|-----------------| | LTS (Long Term Support) | Stable, production-ready version with long-term support | Production applications, enterprise use | | Current | Latest features, more frequent updates | Development, testing new features |
Direct Download Links:
.msi installer (64-bit/32-bit).pkg installer.tar.xz) or via package managerπ§ Installation Guides
Method 1: Direct Installer (Simplest)
**Windows Installation:**
1. Download the Windows installer (.msi) from nodejs.org 2. Double-click the downloaded file 3. Follow the installation wizard 4. Check "Automatically install the necessary tools" for npm and build tools 5. Click "Install" 6. Verify installation:
node --version
npm --version
**macOS Installation:**
1. Download the macOS installer (.pkg) 2. Open the downloaded file 3. Follow the installation instructions 4. Verify installation in Terminal:
node --version
npm --version
**Linux Installation (Ubuntu/Debian):**
# Using NodeSource repository (recommended)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - sudo apt-get install -y nodejs
# Or using APT (may have older version) sudo apt update sudo apt install nodejs npm
# Verify installation node --version npm --version
Method 2: Using NVM (Node Version Manager) - **Recommended for Developers**
NVM allows you to install and switch between multiple Node.js versions.
**Install NVM:**
Windows:
# Download and run the nvm-setup.exe from:
# https://github.com/coreybutler/nvm-windows/releases
macOS/Linux:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
# After installation, either restart terminal or run: export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
**Using NVM:**
# List available Node.js versions
nvm list available
# Install specific version nvm install 20.14.0 # Specific version nvm install --lts # Latest LTS version nvm install node # Latest current version
# List installed versions nvm list
# Use a specific version nvm use 20.14.0
# Set default version nvm alias default 20.14.0
Method 3: Package Managers
**macOS (Homebrew):**
brew install node
**Linux (Various Distributions):**
# Fedora
sudo dnf install nodejs npm
# Arch Linux sudo pacman -S nodejs npm
# Snap (Universal) sudo snap install node --classic
π Getting Started
Your First Node.js Application
1. Create a project directory:
mkdir my-first-app
cd my-first-app
2. Initialize a new Node.js project:
npm init -y
This creates a package.json file with default settings.
3. Create your first JavaScript file:
echo 'console.log("Hello, Node.js!");' > app.js
4. Run your application:
node app.js
# Output: Hello, Node.js!
Understanding `package.json`
When you run npm init, it creates a package.json file:
{
"name": "my-first-app", "version": "1.0.0", "description": "My first Node.js application", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node app.js" }, "keywords": [], "author": "Your Name", "license": "ISC" }
Running Your Application
# Direct execution
node app.js
# Using npm script (defined in package.json) npm start
# For development with auto-restart (install nodemon first) npm install -g nodemon nodemon app.js
π οΈ Working with Node.js
Core Modules (Built-in)
Node.js comes with essential modules you can use without installation:
// File System module
const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
// HTTP module (create web servers) const http = require('http'); http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!'); }).listen(8080);
// Path module const path = require('path'); console.log(path.join(__dirname, 'folder', 'file.txt'));
// OS module const os = require('os'); console.log(`Platform: ${os.platform()}`); console.log(`CPU Cores: ${os.cpus().length}`);
Working with NPM (Node Package Manager)
Installing Packages:
# Install locally (for current project)
npm install package-name
# Install globally (available system-wide) npm install -g package-name
# Install as development dependency npm install --save-dev package-name
# Install specific version npm install [email protected]
Common NPM Commands:
# Initialize new project
npm init
# Install all dependencies from package.json npm install
# Update packages npm update package-name npm update --save
# Uninstall packages npm uninstall package-name
# List installed packages npm list npm list --depth=0 # Show only top-level
# Check for outdated packages npm outdated
# Run scripts npm run script-name
Creating a Web Server
// server.js
const http = require('http');
const server = http.createServer((req, res) => { // Set response header res.writeHead(200, {'Content-Type': 'text/html'});
// Send response based on URL if (req.url === '/') { res.end('<h1>Home Page</h1><p>Welcome to Node.js!</p>'); } else if (req.url === '/about') { res.end('<h1>About Page</h1>'); } else { res.writeHead(404); res.end('<h1>404 Not Found</h1>'); } });
// Start server on port 3000 const PORT = 3000; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
Run with: node server.js
Working with Express.js (Popular Web Framework)
1. Install Express:
npm install express
2. Create an Express app:
// app.js
const express = require('express'); const app = express(); const PORT = 3000;
// Route for home page app.get('/', (req, res) => { res.send('Hello World with Express!'); });
// Route with parameters app.get('/user/:id', (req, res) => { res.send(`User ID: ${req.params.id}`); });
// Start server app.listen(PORT, () => { console.log(`Express server running at http://localhost:${PORT}`); });
π§° Development Tools
Essential Development Packages:
# Development dependencies
npm install --save-dev nodemon # Auto-restart on changes npm install --save-dev eslint # Code linting npm install --save-dev prettier # Code formatting npm install --save-dev jest # Testing framework npm install --save-dev dotenv # Environment variables
Debugging Node.js Applications:
Using Console:
console.log('Regular log');
console.error('Error message'); console.warn('Warning message'); console.table([{name: 'John', age: 30}, {name: 'Jane', age: 25}]);
Using Chrome DevTools:
# Start Node.js in inspect mode
node --inspect app.js
# Or with break on first line node --inspect-brk app.js
chrome://inspect in Chrome browser.
Using VS Code Debugger:
1. Create .vscode/launch.json:
{
"version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/app.js" } ] }
Project Structure Best Practices:
my-project/
βββ src/ β βββ controllers/ # Request handlers β βββ models/ # Data models β βββ routes/ # Route definitions β βββ middleware/ # Custom middleware β βββ utils/ # Helper functions βββ public/ # Static files βββ tests/ # Test files βββ .env # Environment variables (gitignored) βββ .gitignore # Git ignore rules βββ package.json # Project metadata and dependencies βββ README.md # Project documentation βββ app.js # Application entry point
π Troubleshooting Common Issues
1. **Node.js/npm Command Not Found**
# Check if Node.js is in PATH
echo $PATH
# On Windows, you may need to restart after installation # Or manually add to PATH: # C:\Program Files\nodejs\
2. **Permission Errors (Linux/macOS)**
# Fix global npm permissions
sudo chown -R $USER /usr/local/lib/node_modules sudo chown -R $USER /usr/local/bin sudo chown -R $USER /usr/local/share
# Or use a node version manager (nvm) instead
3. **Port Already in Use**
# Find process using port (Linux/macOS)
lsof -i :3000
# Windows netstat -ano | findstr :3000
# Kill process kill -9 PID # Linux/macOS taskkill /PID PID /F # Windows
4. **npm Install Errors**
# Clear npm cache
npm cache clean --force
# Delete node_modules and package-lock.json rm -rf node_modules package-lock.json
# Reinstall npm install
5. **Version Compatibility Issues**
# Check Node.js and npm versions
node --version npm --version
# Update npm npm install -g npm@latest
# Use nvm to switch Node.js versions nvm install 18.19.0 nvm use 18.19.0
6. **Memory Issues**
# Increase memory limit for Node.js
node --max-old-space-size=4096 app.js
# Set environment variable (permanent) export NODE_OPTIONS=--max-old-space-size=4096
π Additional Resources
Official Documentation:
Learning Platforms:
Popular Frameworks and Libraries:
Community and Support:
π― Best Practices
1. Always use version control (git) for your projects 2. Use .gitignore to exclude node_modules and sensitive files 3. Specify exact versions or use semantic versioning in package.json 4. Use environment variables for configuration (never hardcode secrets) 5. Implement proper error handling and logging 6. Write tests for your code 7. Use ESLint and Prettier for code quality 8. Keep dependencies updated (use npm audit and npm outdated) 9. Document your code and write clear README files 10. Use async/await for better asynchronous code readability
π¦ Sample Project Checklist
When starting a new Node.js project:
npm init.gitignorepackage.jsonNode.js is a free, open-source, cross-platform JavaScript runtime environment that allows developers to run JavaScript outside of a web browser .
No language data available