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 axiosThen 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
- Visit the official Node.js website: https://nodejs.org
- You'll see two download buttons:
- LTS (Recommended for most users) - Click this one
- Current (Latest features)
- Click the LTS button to download the Windows installer (.msi file)
Step 2: Run the Installer
- Locate the downloaded file (usually in your Downloads folder)
- Double-click the
.msifile to start installation - Click Next on the welcome screen
Step 3: Accept License Agreement
- Read the license agreement
- Check "I accept the terms in the License Agreement"
- Click Next
Step 4: Choose Installation Location
- Default location is usually fine:
C:\Program Files\nodejs\ - Click Next
Step 5: Custom Setup
- Keep all default features selected:
- Node.js runtime
- npm package manager
- Online documentation shortcuts
- Add to PATH (very important!)
- Click Next
Step 6: Tools for Native Modules (Optional)
- You'll see an option to install tools for native modules
- For beginners, you can skip this (uncheck the box)
- Click Next
Step 7: Install
- Click Install
- Wait for the installation to complete (1-2 minutes)
- Click Finish
Step 8: Verify Installation
- Open Command Prompt (Press
Win + R, typecmd, press Enter) - Type the following commands:
node --versionYou should see something like: v20.11.0
npm --versionYou 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
- Visit https://nodejs.org
- Click the LTS button to download the macOS installer (.pkg file)
Step 2: Run the Installer
- Open the downloaded
.pkgfile - Click Continue on the welcome screen
- Accept the license agreement
- Choose installation location (default is fine)
- Click Install
- Enter your Mac password when prompted
- Wait for installation to complete
- Click Close
Step 3: Verify Installation
- Open Terminal (Press
Cmd + Space, type "Terminal", press Enter) - Type these commands:
node --versionExpected output: v20.11.0 (or similar)
npm --versionExpected 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 nodeStep 3: Verify Installation
node --version
npm --versionAdvantages 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 updateStep 2: Install Prerequisites
sudo apt install -y curlStep 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 nodejsThis command installs both Node.js and npm.
Step 5: Verify Installation
node --version
npm --versionMethod 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 npmOther Linux Distributions
Fedora:
sudo dnf install nodejs npmCentOS:
sudo yum install nodejs npmArch Linux:
sudo pacman -S nodejs npmVerifying 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 --versionor the shorter form:
node -vExpected output: v20.11.0 (your version number may differ)
Check npm Version
npm --versionor:
npm -vExpected output: 10.2.4 (your version number may differ)
Test Node.js REPL
Type node and press Enter:
nodeYou 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:
- Search for "Environment Variables" in Windows search
- Click "Edit the system environment variables"
- Click "Environment Variables" button
- Under "System variables", find "Path"
- Click "Edit"
- Add Node.js path:
C:\Program Files\nodejs\ - 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_profileIssue 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 ~/.profileIssue 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 nodeLinux:
sudo apt remove nodejs
# Then follow installation steps againRunning 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-learningmacOS/Linux:
mkdir ~/javascript-learning
cd ~/javascript-learningStep 2: Create Your First JavaScript File
Create a file called hello.js:
Windows (Command Prompt):
echo console.log("Hello from Node.js!"); > hello.jsmacOS/Linux or Windows PowerShell:
echo 'console.log("Hello from Node.js!");' > hello.jsOr use a text editor:
- Open Notepad (Windows) or TextEdit (Mac)
- Type:
console.log("Hello from Node.js!"); - Save as
hello.jsin your project folder
Step 3: Run Your JavaScript File
In your terminal, run:
node hello.jsOutput:
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.jsOutput:
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:
nodeYou'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
> _
20Special 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
- Open VS Code
- File → Open Folder
- Select your
javascript-learningfolder
Step 2: Create a New File
- Click "New File" icon or press
Ctrl+N(Windows/Linux) orCmd+N(Mac) - Save as
test.js
Step 3: Write Some Code
const message = "Hello from VS Code!";
console.log(message);Step 4: Run Your Code
- Open integrated terminal:
Ctrl +` (backtick) or View → Terminal - Type:
node test.js - 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 initThis 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 -yThis 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 projectdescription: What your project doesmain: Entry point filescripts: Custom commands you can run withnpm rundependencies: Packages your project needs to rundevDependencies: Packages needed only for development
Installing Packages
Install a package and add to dependencies:
npm install package-nameExample: Install lodash (utility library)
npm install lodashThis will:
- Download the package
- Create
node_modulesfolder - Add lodash to
package.jsondependencies - 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: 15Run it:
node test-lodash.jsUnderstanding node_modules
After installing packages, you'll see a node_modules folder. This contains all installed packages and their dependencies.
Important notes:
node_modulescan be very large (hundreds of MBs)- Never edit files inside
node_modules - Don't commit
node_modulesto Git (add to.gitignore) - Can be recreated with
npm install
Other Useful npm Commands
Install specific version:
npm install lodash@4.17.21Install as dev dependency:
npm install --save-dev eslintUninstall a package:
npm uninstall package-nameUpdate packages:
npm updateList installed packages:
npm listList outdated packages:
npm outdatedRun scripts defined in package.json:
npm run script-nameQuick 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-projectStep 2: Initialize npm
npm init -yStep 3: Install a Package
npm install chalkChalk 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 startYou 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 startUseful Links
- Node.js Official Website: https://nodejs.org
- npm Official Website: https://www.npmjs.com
- Node.js Documentation: https://nodejs.org/docs
- VS Code Download: https://code.visualstudio.com
Practice Exercise
Before moving to the next section, try this:
Challenge: Create a simple greeting program
- Create a new folder called
greeting-app - Initialize npm with
npm init -y - Create
app.jsfile - 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"
- Run it with
node app.js
Bonus: Install the chalk package and make your output colorful!