JavaScript Tutorial

Node.js Installation Guide: Complete Setup for Beginners

Learn how to install Node.js and npm on Windows, macOS, and Linux. Complete step-by-step guide with verification, troubleshooting, and running your first Node.js program.

Welcome back! 👋 In the previous lessons, we learned what JavaScript is and how it executes. Now it's time to set up your development environment so you can start writing and running JavaScript code on your computer.

In this guide, you'll learn how to install Node.js and npm, verify the installation, and run your first JavaScript program outside the browser. Let's get started!


What is Node.js?

Node.js is a JavaScript runtime environment that allows you to run JavaScript code outside of a web browser. It's built on Chrome's V8 JavaScript engine and enables JavaScript to be used for server-side programming.

Key Points About Node.js

Before Node.js (Pre-2009):

  • JavaScript could only run in web browsers
  • Limited to client-side interactions (DOM manipulation, form validation)
  • Couldn't access file systems, databases, or create servers

After Node.js (2009-Present):

  • JavaScript can run on servers and computers
  • Build backend APIs, command-line tools, and desktop apps
  • Access file systems, databases, and network operations
  • Use the same language (JavaScript) for frontend and backend

Real-World Uses of Node.js

Node.js is used by major companies for various purposes:

Netflix: Reduced startup time by 70% using Node.js for their UI
PayPal: Built their payment processing system with Node.js
LinkedIn: Mobile backend runs on Node.js
Uber: Handles massive amounts of data with Node.js
NASA: Uses Node.js for data analysis and mission-critical systems
Walmart: Powers their e-commerce platform backend

Common Use Cases:

  • Building REST APIs and GraphQL servers
  • Real-time applications (chat apps, live notifications)
  • Microservices architecture
  • Command-line tools and automation scripts
  • Server-side rendering for React/Vue applications
  • Data streaming applications
  • IoT (Internet of Things) applications

What is npm (Node Package Manager)?

When you install Node.js, you also get npm (Node Package Manager) automatically. npm is the world's largest software registry with over 2 million packages.

What Does npm Do?

Think of npm as an app store for JavaScript code. Just like you download apps from the App Store or Google Play, developers use npm to download and share code packages.

npm allows you to:

  • Install third-party libraries and frameworks (React, Express, Lodash, etc.)
  • Manage project dependencies
  • Share your own code packages with others
  • Run scripts and automate tasks
  • Version control for packages

Example: Instead of writing code to make HTTP requests from scratch, you can install a package like axios:

npm install axios

Then use it in your code:

const axios = require('axios');

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data));

npm vs Other Package Managers

While npm is the default, there are alternatives:

  • npm (default) - Comes with Node.js, widely used
  • Yarn - Created by Facebook, faster in some cases
  • pnpm - Efficient disk space usage, faster installations

For beginners: Start with npm. It's the standard and most widely documented.


What is a Runtime Environment?

A runtime environment is where your code executes. It provides all the necessary components to run your programs.

Browser Runtime vs Node.js Runtime

Browser Runtime:

  • Has access to DOM (Document Object Model)
  • Window object, localStorage, cookies
  • Limited file system access (security reasons)
  • Can't create servers or databases
// Browser-specific code
document.getElementById('myButton').addEventListener('click', () => {
  alert('Button clicked!');
});

Node.js Runtime:

  • No DOM or window object (no browser features)
  • Access to file system, operating system, network
  • Can create HTTP servers
  • Run command-line tools
// Node.js-specific code
const fs = require('fs');

fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

The V8 Engine

Both Chrome browser and Node.js use Google's V8 JavaScript engine. V8 compiles JavaScript to machine code for fast execution.

What V8 does:

  • Parses JavaScript code
  • Compiles it to optimized machine code
  • Executes the code efficiently
  • Manages memory (garbage collection)

Node.js = V8 Engine + Additional APIs (file system, HTTP, OS modules, etc.)


System Requirements

Before installing Node.js, ensure your system meets these requirements:

Operating System

Windows:

  • Windows 10 or later (64-bit recommended)
  • Windows 8.1, 8, 7 (older Node.js versions)

macOS:

  • macOS 10.15 (Catalina) or later
  • Works on both Intel and Apple Silicon (M1/M2/M3) Macs

Linux:

  • Ubuntu 18.04 or later
  • Debian, CentOS, Fedora, and other major distributions

Hardware Requirements

Minimum:

  • 2 GB RAM
  • 200 MB free disk space (for Node.js installation)
  • Any modern processor (Intel, AMD, ARM)

Recommended:

  • 4 GB RAM or more
  • 1 GB free disk space (for Node.js + packages)
  • Multi-core processor for better performance

Note: Node.js is lightweight and will run on most modern computers without issues.


Choosing the Right Node.js Version

Node.js releases new versions regularly. You'll see two main types:

LTS vs Current Version

LTS (Long Term Support) - RECOMMENDED for beginners

  • Stable and well-tested
  • Gets security updates for 30 months
  • Recommended for production applications
  • Even-numbered versions (18.x, 20.x, 22.x)
  • This is what you should install

Current Version

  • Latest features and improvements
  • Gets updates for 6 months
  • May have bugs or breaking changes
  • Odd-numbered versions (19.x, 21.x, 23.x)
  • Good for experimenting with new features

Version Numbering Explained

Node.js uses semantic versioning: MAJOR.MINOR.PATCH

Example: v20.11.0

  • 20 = Major version (breaking changes)
  • 11 = Minor version (new features, backward compatible)
  • 0 = Patch version (bug fixes)

For this tutorial, install the latest LTS version (currently v20.x or v22.x).


Installation Instructions

Let's install Node.js on your system. Choose your operating system below:

Option 1: Windows Installation

Step 1: Download Node.js

  1. Visit the official Node.js website: https://nodejs.org
  2. You'll see two download buttons:
    • LTS (Recommended for most users) - Click this one
    • Current (Latest features)
  3. Click the LTS button to download the Windows installer (.msi file)

Step 2: Run the Installer

  1. Locate the downloaded file (usually in your Downloads folder)
  2. Double-click the .msi file to start installation
  3. Click Next on the welcome screen

Step 3: Accept License Agreement

  1. Read the license agreement
  2. Check "I accept the terms in the License Agreement"
  3. Click Next

Step 4: Choose Installation Location

  1. Default location is usually fine: C:\Program Files\nodejs\
  2. Click Next

Step 5: Custom Setup

  1. Keep all default features selected:
    • Node.js runtime
    • npm package manager
    • Online documentation shortcuts
    • Add to PATH (very important!)
  2. Click Next

Step 6: Tools for Native Modules (Optional)

  1. You'll see an option to install tools for native modules
  2. For beginners, you can skip this (uncheck the box)
  3. Click Next

Step 7: Install

  1. Click Install
  2. Wait for the installation to complete (1-2 minutes)
  3. Click Finish

Step 8: Verify Installation

  1. Open Command Prompt (Press Win + R, type cmd, press Enter)
  2. Type the following commands:
node --version

You should see something like: v20.11.0

npm --version

You should see something like: 10.2.4

If you see version numbers, congratulations! Node.js is installed successfully! 🎉


Option 2: macOS Installation

You have two methods to install Node.js on macOS:

Method 1: Official Installer (Easier for Beginners)

Step 1: Download Node.js

  1. Visit https://nodejs.org
  2. Click the LTS button to download the macOS installer (.pkg file)

Step 2: Run the Installer

  1. Open the downloaded .pkg file
  2. Click Continue on the welcome screen
  3. Accept the license agreement
  4. Choose installation location (default is fine)
  5. Click Install
  6. Enter your Mac password when prompted
  7. Wait for installation to complete
  8. Click Close

Step 3: Verify Installation

  1. Open Terminal (Press Cmd + Space, type "Terminal", press Enter)
  2. Type these commands:
node --version

Expected output: v20.11.0 (or similar)

npm --version

Expected output: 10.2.4 (or similar)

Method 2: Using Homebrew (Recommended for Developers)

If you already have Homebrew installed, this method is cleaner and easier to update.

Step 1: Install Homebrew (if not already installed)

Open Terminal and run:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 2: Install Node.js

brew install node

Step 3: Verify Installation

node --version
npm --version

Advantages of Homebrew method:

  • Easy updates: brew upgrade node
  • Easy uninstall: brew uninstall node
  • Manages dependencies automatically

Option 3: Linux Installation (Ubuntu/Debian)

Method 1: Using NodeSource Repository (Recommended)

This method gives you the latest LTS version.

Step 1: Update Package Index

Open Terminal and run:

sudo apt update

Step 2: Install Prerequisites

sudo apt install -y curl

Step 3: Add NodeSource Repository

For Node.js 20.x LTS:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -

Step 4: Install Node.js

sudo apt install -y nodejs

This command installs both Node.js and npm.

Step 5: Verify Installation

node --version
npm --version

Method 2: Using Default Ubuntu Repository (Older Version)

Note: This installs an older version. Use Method 1 for the latest.

sudo apt update
sudo apt install nodejs npm

Other Linux Distributions

Fedora:

sudo dnf install nodejs npm

CentOS:

sudo yum install nodejs npm

Arch Linux:

sudo pacman -S nodejs npm

Verifying Your Installation

After installation, it's important to verify everything is working correctly.

Check Node.js Version

Open your terminal/command prompt and run:

node --version

or the shorter form:

node -v

Expected output: v20.11.0 (your version number may differ)

Check npm Version

npm --version

or:

npm -v

Expected output: 10.2.4 (your version number may differ)

Test Node.js REPL

Type node and press Enter:

node

You should see something like:

Welcome to Node.js v20.11.0.
Type ".help" for more information.
>

This is the Node.js REPL (Read-Eval-Print Loop). Try a simple calculation:

> 2 + 2
4
> console.log("Hello, Node.js!")
Hello, Node.js!
undefined
>

To exit the REPL, press Ctrl + C twice or type .exit and press Enter.


Common Installation Issues and Fixes

Issue 1: "node is not recognized" or "command not found"

Problem: Node.js is not in your system PATH.

Solution for Windows:

  1. Search for "Environment Variables" in Windows search
  2. Click "Edit the system environment variables"
  3. Click "Environment Variables" button
  4. Under "System variables", find "Path"
  5. Click "Edit"
  6. Add Node.js path: C:\Program Files\nodejs\
  7. Click OK and restart Command Prompt

Solution for macOS/Linux: Add to your .bash_profile or .zshrc:

export PATH="/usr/local/bin:$PATH"

Then run:

source ~/.bash_profile

Issue 2: Permission Errors on macOS/Linux

Problem: npm install commands fail with permission errors.

Solution: Never use sudo with npm. Instead, configure npm to use a different directory:

mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile
source ~/.profile

Issue 3: Old Version Installed

Problem: node -v shows an old version after installing latest.

Solution:

Windows: Uninstall old version from Control Panel, then reinstall.

macOS with Homebrew:

brew upgrade node

Linux:

sudo apt remove nodejs
# Then follow installation steps again

Running Your First Node.js Program

Now that Node.js is installed, let's write and run your first JavaScript program!

Step 1: Create a Project Folder

Create a folder for your JavaScript projects:

Windows:

mkdir C:\Users\YourName\Documents\javascript-learning
cd C:\Users\YourName\Documents\javascript-learning

macOS/Linux:

mkdir ~/javascript-learning
cd ~/javascript-learning

Step 2: Create Your First JavaScript File

Create a file called hello.js:

Windows (Command Prompt):

echo console.log("Hello from Node.js!"); > hello.js

macOS/Linux or Windows PowerShell:

echo 'console.log("Hello from Node.js!");' > hello.js

Or use a text editor:

  1. Open Notepad (Windows) or TextEdit (Mac)
  2. Type: console.log("Hello from Node.js!");
  3. Save as hello.js in your project folder

Step 3: Run Your JavaScript File

In your terminal, run:

node hello.js

Output:

Hello from Node.js!

🎉 Congratulations! You just ran your first Node.js program!

Step 4: Try a More Complex Example

Create a file called calculator.js:

// calculator.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  return a * b;
}

function divide(a, b) {
  if (b === 0) {
    return "Cannot divide by zero!";
  }
  return a / b;
}

// Test the functions
console.log("Addition: 5 + 3 =", add(5, 3));
console.log("Subtraction: 10 - 4 =", subtract(10, 4));
console.log("Multiplication: 6 * 7 =", multiply(6, 7));
console.log("Division: 20 / 5 =", divide(20, 5));
console.log("Division by zero: 10 / 0 =", divide(10, 0));

Run it:

node calculator.js

Output:

Addition: 5 + 3 = 8
Subtraction: 10 - 4 = 6
Multiplication: 6 * 7 = 42
Division: 20 / 5 = 4
Division by zero: 10 / 0 = Cannot divide by zero!

Understanding the Node.js REPL

REPL stands for Read-Eval-Print Loop. It's an interactive programming environment.

Accessing the REPL

Simply type node in your terminal:

node

You'll see:

>

This prompt means Node.js is waiting for your input.

REPL Features

1. Execute JavaScript directly:

> let name = "Mihir"
undefined
> console.log("Hello, " + name)
Hello, Mihir
undefined
> name.toUpperCase()
'MIHIR'

2. Multi-line input:

> function greet(name) {
... return `Hello, ${name}!`;
... }
undefined
> greet("World")
'Hello, World!'

3. Access previous results with _ (underscore):

> 5 + 5
10
> _ + 10
20
> _
20

Special REPL Commands

  • .help - Show all REPL commands
  • .break - Exit multi-line input
  • .clear - Reset REPL context
  • .exit - Exit REPL (or press Ctrl+C twice)
  • .save filename - Save current session to a file
  • .load filename - Load JavaScript from a file

When to Use REPL vs Files

Use REPL for:

  • Quick calculations or tests
  • Experimenting with JavaScript syntax
  • Testing small code snippets
  • Learning and exploring

Use Files for:

  • Writing actual programs
  • Code you want to save and reuse
  • Complex logic with multiple functions
  • Projects and applications

Setting Up Your Development Environment

To write JavaScript code efficiently, you need a good code editor.

Recommended Code Editor: Visual Studio Code

Why VS Code?

  • Free and open-source
  • Excellent JavaScript support
  • Built-in terminal
  • Extensions for everything
  • IntelliSense (code completion)
  • Debugging tools

Download VS Code: Visit https://code.visualstudio.com

Essential VS Code Extensions for JavaScript

After installing VS Code, add these extensions:

1. ESLint

  • Finds and fixes JavaScript errors
  • Enforces coding standards
  • Install: Search "ESLint" in Extensions panel

2. Prettier - Code Formatter

  • Automatically formats your code
  • Consistent code style
  • Install: Search "Prettier"

3. JavaScript (ES6) code snippets

  • Quick code templates
  • Speeds up development
  • Install: Search "JavaScript (ES6) code snippets"

4. Path Intellisense

  • Autocompletes file paths
  • Useful for imports
  • Install: Search "Path Intellisense"

5. Live Server (for browser-based JavaScript)

  • Launch local development server
  • Auto-refresh on save
  • Install: Search "Live Server"

VS Code Setup

Step 1: Open Your Project Folder

  1. Open VS Code
  2. File → Open Folder
  3. Select your javascript-learning folder

Step 2: Create a New File

  1. Click "New File" icon or press Ctrl+N (Windows/Linux) or Cmd+N (Mac)
  2. Save as test.js

Step 3: Write Some Code

const message = "Hello from VS Code!";
console.log(message);

Step 4: Run Your Code

  1. Open integrated terminal: Ctrl + ` (backtick) or View → Terminal
  2. Type: node test.js
  3. See the output in the terminal!

Basic npm Commands

Let's learn some essential npm commands you'll use frequently.

Initializing a Project

Create a package.json file (project configuration):

npm init

This will ask you several questions:

  • package name: (your-project-name)
  • version: (1.0.0)
  • description: A simple JavaScript project
  • entry point: (index.js)
  • test command:
  • git repository:
  • keywords:
  • author: Your Name
  • license: (ISC)

Quick initialization (skip questions):

npm init -y

This creates a package.json with default values.

Understanding package.json

After running npm init, you'll have a package.json file:

{
  "name": "javascript-learning",
  "version": "1.0.0",
  "description": "Learning JavaScript with Node.js",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Mihir",
  "license": "ISC"
}

What each field means:

  • name: Your project name (lowercase, no spaces)
  • version: Current version of your project
  • description: What your project does
  • main: Entry point file
  • scripts: Custom commands you can run with npm run
  • dependencies: Packages your project needs to run
  • devDependencies: Packages needed only for development

Installing Packages

Install a package and add to dependencies:

npm install package-name

Example: Install lodash (utility library)

npm install lodash

This will:

  1. Download the package
  2. Create node_modules folder
  3. Add lodash to package.json dependencies
  4. Create package-lock.json (locks exact versions)

Using the installed package:

// test-lodash.js
const _ = require('lodash');

const numbers = [1, 2, 3, 4, 5];
const sum = _.sum(numbers);

console.log("Sum:", sum); // Output: Sum: 15

Run it:

node test-lodash.js

Understanding node_modules

After installing packages, you'll see a node_modules folder. This contains all installed packages and their dependencies.

Important notes:

  • node_modules can be very large (hundreds of MBs)
  • Never edit files inside node_modules
  • Don't commit node_modules to Git (add to .gitignore)
  • Can be recreated with npm install

Other Useful npm Commands

Install specific version:

npm install lodash@4.17.21

Install as dev dependency:

npm install --save-dev eslint

Uninstall a package:

npm uninstall package-name

Update packages:

npm update

List installed packages:

npm list

List outdated packages:

npm outdated

Run scripts defined in package.json:

npm run script-name

Quick Start: Your First npm Project

Let's create a complete mini-project to practice everything!

Step 1: Create Project Folder

mkdir my-first-project
cd my-first-project

Step 2: Initialize npm

npm init -y

Step 3: Install a Package

npm install chalk

Chalk is a package for styling terminal output with colors.

Step 4: Create index.js

// index.js
const chalk = require('chalk');

console.log(chalk.blue('Hello, World!'));
console.log(chalk.red.bold('This is bold red text'));
console.log(chalk.green.underline('This is underlined green text'));
console.log(chalk.yellow.bgBlue('Yellow text with blue background'));

console.log('\n' + chalk.cyan('My First Node.js Project! 🚀'));

Step 5: Add a Script to package.json

Edit your package.json and add a "start" script:

{
  "name": "my-first-project",
  "version": "1.0.0",
  "description": "My first Node.js project",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Your Name",
  "license": "ISC",
  "dependencies": {
    "chalk": "^4.1.2"
  }
}

Step 6: Run Your Project

npm start

You should see colorful output in your terminal! 🎨


Key Takeaways

Congratulations! You've successfully set up your Node.js development environment. Here's what you learned:

What Node.js is and why it's important for JavaScript development

What npm is and how it manages packages

How to install Node.js on Windows, macOS, and Linux

How to verify installation and troubleshoot common issues

How to run JavaScript files outside the browser

Using the Node.js REPL for quick experiments

Setting up VS Code with essential extensions

Basic npm commands for managing projects and packages

Creating your first npm project from scratch


What's Next?

Now that you have Node.js installed and understand the basics of npm, you're ready to dive into JavaScript Fundamentals!

In the next section, you'll learn:

  • Variables and Data Types
  • Operators and Expressions
  • Control Flow (if/else, switch)
  • Loops and Iteration
  • Functions and Scope
  • And much more!

You now have all the tools you need to start your JavaScript journey. The real learning begins now! 🚀


Quick Reference

Essential Commands

# Check versions
node --version
npm --version

# Run JavaScript file
node filename.js

# Start REPL
node

# Initialize project
npm init -y

# Install package
npm install package-name

# Run script
npm start

Useful Links


Practice Exercise

Before moving to the next section, try this:

Challenge: Create a simple greeting program

  1. Create a new folder called greeting-app
  2. Initialize npm with npm init -y
  3. Create app.js file
  4. Write a program that:
    • Stores your name in a variable
    • Stores your age in a variable
    • Uses console.log to print: "Hello, my name is [name] and I am [age] years old"
  5. Run it with node app.js

Bonus: Install the chalk package and make your output colorful!