Skip to main content

Command Palette

Search for a command to run...

Setting Up Your First Node.js Application Step-by-Step

Updated
13 min read
Setting Up Your First Node.js Application Step-by-Step
H
CS undergrad | Tech enthusiast | Focusing on Web Dev • DSA • ML | Building skills for real-world impact

Node.js is JavaScript outside the browser. You can run JavaScript on your computer, on servers, and in the cloud. Getting started is simpler than you think. This guide walks you through everything from zero.

This is about installing Node.js, understanding what it does, running your first script, and building your first server.


What Is Node.js?

Node.js is a JavaScript runtime. It lets you run JavaScript code outside the browser.

JavaScript Before Node.js

Browser
    ↓
  JavaScript engine
    ↓
  Runs scripts, handles DOM, events

JavaScript was trapped in the browser. You needed a browser to run JavaScript.

JavaScript with Node.js

Computer / Server
    ↓
  Node.js (JavaScript runtime)
    ↓
  Runs scripts, handles files, networks, databases

Now JavaScript runs anywhere. No browser needed.

What Can Node.js Do?

  • Create web servers
  • Read and write files
  • Make HTTP requests
  • Connect to databases
  • Run command-line tools
  • Build APIs
  • Process data

Basically anything a server-side language can do.


Installing Node.js

Node.js is free and open-source. Installation takes 2 minutes.

Step 1: Go to nodejs.org

Visit https://nodejs.org/

You'll see two versions:

LTS (Long Term Support)  ← Recommended for beginners
Current                  ← Latest features, less stable

Download the LTS version. It's stable and supported for years.

Step 2: Run the Installer

Windows:

  1. Download the .msi file
  2. Run the installer
  3. Click "Next" through the steps
  4. Click "Install"
  5. Click "Finish"

macOS:

  1. Download the .pkg file
  2. Run the installer
  3. Follow the prompts
  4. Done

Linux (Ubuntu/Debian):

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

Or use your package manager.

Step 3: Verify Installation

Open a terminal/command prompt and type:

node --version

You should see:

v20.10.0

(The exact version doesn't matter, just that it shows a version.)

Also check npm:

npm --version

You should see:

10.2.3

Both commands working? Node.js is installed. You're done.


Understanding the Terminal

You'll need to use the terminal (command line) to run Node.js scripts.

Opening the Terminal

Windows:

  • Press Win + R
  • Type cmd
  • Press Enter

macOS:

  • Press Cmd + Space
  • Type terminal
  • Press Enter

Linux:

  • Ctrl + Alt + T
  • Or search for "Terminal"

Basic Commands

pwd                 # Print working directory (where you are)
ls                  # List files in current directory
cd folder_name      # Change directory (go into a folder)
cd ..               # Go up one level
mkdir folder_name   # Make a new folder

Example

pwd
# Output: /Users/john/Documents

ls
# Output: Desktop  Documents  Downloads

cd Documents
# Now you're in Documents folder

pwd
# Output: /Users/john/Documents

mkdir my-app
cd my-app
# Now you're in my-app folder

The Node REPL

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

What Is REPL?

Read   → You type JavaScript code
Eval   → Node.js evaluates it
Print  → It prints the result
Loop   → Waits for more input

It's like a JavaScript sandbox where you can test code instantly.

Starting the REPL

Type this in your terminal:

node

You'll see:

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

The > prompt means Node is waiting for input.

Using the REPL

Try some JavaScript:

> 2 + 2
4
> "hello"
'hello'
> const name = "John"
undefined
> name
'John'

The REPL evaluates each line and prints the result. undefined is printed when there's nothing to return (like after assignment).

REPL Examples

> const numbers = [1, 2, 3]
undefined

> numbers.length
3

> numbers.map(n => n * 2)
[ 2, 4, 6 ]

> Math.sqrt(16)
4

> new Date()
2026-05-04T10:30:45.123Z

Exiting the REPL

Type .exit or press Ctrl + D:

> .exit

You're back at the terminal prompt.

REPL Is for Experimenting

The REPL is great for:

  • Testing code quickly
  • Learning JavaScript
  • Debugging
  • Exploring APIs

But for real applications, you write code in files.


Your First Node.js Script

Let's create a simple JavaScript file and run it with Node.

Step 1: Create a Folder

mkdir my-first-app
cd my-first-app

You're now in a new folder.

Step 2: Create a JavaScript File

Create a file named hello.js:

Windows (Command Prompt):

type nul > hello.js

macOS/Linux:

touch hello.js

Or use a text editor (VS Code, Sublime Text, etc.) to create the file.

Step 3: Write Code

Open hello.js in your text editor and write:

console.log("Hello, World!");

Save the file.

Step 4: Run the Script

In your terminal (in the same folder), type:

node hello.js

You'll see:

Hello, World!

Success! You just ran your first Node.js script.

What Happened?

You type: node hello.js
    ↓
Node reads hello.js
    ↓
Node executes the code
    ↓
console.log() prints to terminal
    ↓
Output: Hello, World!
    ↓
Script finishes, returns to prompt

More Examples

Example 1: Variables and Math

Create math.js:

const a = 10;
const b = 20;
const sum = a + b;

console.log("Sum:", sum);
console.log("Product:", a * b);

Run it:

node math.js

Output:

Sum: 30
Product: 200

Example 2: Arrays and Loops

Create loop.js:

const fruits = ["apple", "banana", "orange"];

console.log("Fruits:");
for (let fruit of fruits) {
  console.log("- " + fruit);
}

Run it:

node loop.js

Output:

Fruits:
- apple
- banana
- orange

Example 3: Functions

Create greet.js:

function greet(name, age) {
  console.log("Hello, " + name + "!");
  console.log("You are " + age + " years old.");
}

greet("Alice", 25);
greet("Bob", 30);

Run it:

node greet.js

Output:

Hello, Alice!
You are 25 years old.
Hello, Bob!
You are 30 years old.

Node.js Execution Flow

Here's what happens when you run a script.

Execution Timeline

You type: node hello.js
    ↓
1. Node.js starts
    ↓
2. Reads hello.js
    ↓
3. Parses the code (checks for syntax errors)
    ↓
4. Executes the code line by line
    ↓
5. Encounters console.log()
    ↓
6. Prints output to terminal
    ↓
7. Code finishes
    ↓
8. Node.js exits
    ↓
Back to terminal prompt

Script → Runtime → Output Flow

hello.js (file)
    ↓
Node.js Runtime
    ↓
JavaScript Engine (V8)
    ↓
Parse code
    ↓
Execute code
    ↓
Call built-in functions (console.log, etc.)
    ↓
Output: "Hello, World!"

Why Files vs REPL?

REPL is interactive:

  • Type one line
  • See result immediately
  • Good for learning

Files are permanent:

  • Code is saved
  • Can run anytime
  • Easy to share
  • Good for real projects

Writing Your First Server

Now let's create a real Node.js server. It won't be much, but it's a real web server.

What Is a Server?

A server is a program that listens for requests and sends responses.

Client (browser/computer)
    ↓
Sends request to server
    ↓
Server
    ↓
Receives request
Processes it
Sends response
    ↓
Client
    ↓
Receives response

Hello World Server

Create server.js:

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, World!");
});

server.listen(3000);
console.log("Server running on http://localhost:3000");

Running the Server

node server.js

You'll see:

Server running on http://localhost:3000

The server is now running. It won't stop until you stop it (which you'll do in a moment).

Testing the Server

Open your browser and go to:

http://localhost:3000

You'll see:

Hello, World!

The server responded! You made a request, the server processed it, and sent back a response.

Stopping the Server

In the terminal, press Ctrl + C:

^C

The server stops. You're back at the prompt.

Breaking Down the Code

const http = require("http");

This imports Node's built-in http module. It lets you create web servers.

const server = http.createServer((req, res) => {
  // This function runs every time a request comes in
});

createServer() creates a server. The function (callback) runs for each request.

res.writeHead(200, { "Content-Type": "text/plain" });

writeHead() sends the response header. 200 means "OK" (success). The second argument specifies the content type.

res.end("Hello, World!");

end() sends the response body and closes the connection.

server.listen(3000);

listen() makes the server listen on port 3000. Your browser connects to localhost:3000.

console.log("Server running on http://localhost:3000");

Print a message so you know the server started.

Server with Different Paths

Let's make a server that responds differently based on the URL path.

Create server-routes.js:

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    res.writeHead(200);
    res.end("Home page");
  } else if (req.url === "/about") {
    res.writeHead(200);
    res.end("About page");
  } else if (req.url === "/contact") {
    res.writeHead(200);
    res.end("Contact page");
  } else {
    res.writeHead(404);
    res.end("Page not found");
  }
});

server.listen(3000);
console.log("Server running on http://localhost:3000");

Run it:

node server-routes.js

Now try:

  • http://localhost:3000/ → "Home page"
  • http://localhost:3000/about → "About page"
  • http://localhost:3000/contact → "Contact page"
  • http://localhost:3000/other → "Page not found"

Each path gives a different response.

Server with HTML

Let's send actual HTML instead of plain text.

Create server-html.js:

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/html" });
  
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>My Node Server</title>
    </head>
    <body>
      <h1>Welcome to My Node Server</h1>
      <p>This HTML is served from Node.js</p>
    </body>
    </html>
  `;
  
  res.end(html);
});

server.listen(3000);
console.log("Server running on http://localhost:3000");

Run it:

node server-html.js

Visit http://localhost:3000 and you'll see a proper HTML page in your browser.


Project Structure

As your projects grow, organize your files.

Simple Structure

my-app/
  ├── server.js
  ├── helpers.js
  └── data.json

Everything in one folder.

Better Structure

my-app/
  ├── src/
  │   ├── server.js
  │   ├── handlers.js
  │   └── utils.js
  ├── data/
  │   └── data.json
  ├── public/
  │   ├── style.css
  │   └── index.html
  └── package.json

Organized by purpose.


Node.js Execution Flow Diagram

Write Code
    ↓
hello.js file created
    ↓
terminal: node hello.js
    ↓
Node.js starts
    ↓
Read hello.js from disk
    ↓
Parse JavaScript
    ↓
Execute code
    ↓
    ├─ Variable declarations
    ├─ Function calls
    └─ I/O operations
    ↓
Output to terminal/console
    ↓
Script finishes
    ↓
Process exits
    ↓
Back to terminal prompt

Common Questions

Q: What's the difference between Node.js and npm?

Node.js is the JavaScript runtime.

npm is the Node Package Manager. It lets you install libraries and tools.

node --version    # Check Node.js
npm --version     # Check npm

Q: Why does Node.js need a port number?

Your computer can run multiple servers. Each server needs a unique port.

Port 3000 → My app
Port 5000 → Another app
Port 8080 → Another app

A port is like an address on your computer.

Q: Can I use Node.js with HTML/CSS?

Yes. Node.js can serve HTML and CSS files. Or you can use frameworks like Express to make it easier.

Q: Is Node.js used only for web servers?

No. You can:

  • Build web servers
  • Create command-line tools
  • Process files
  • Build real-time applications
  • Automate tasks
  • And much more

Q: Do I need a framework like Express?

Not at all. You can build servers with just Node's built-in modules. But Express makes it easier.

Q: Can I run Node.js code in the browser?

No. Node.js runs on servers/your computer. Browser JavaScript is different. They have different APIs.


Practice Assignment

1. Install Node.js and verify:

node --version
npm --version

Both should print version numbers.

2. Try the REPL:

node
> 5 + 5
> "hello " + "world"
> const name = "John"
> name.toUpperCase()
> .exit

Experiment with different JavaScript.

3. Create your first script:

Create welcome.js:

const name = "Your Name";
console.log("Welcome, " + name);
console.log("You are now a Node.js developer!");

Run it:

node welcome.js

4. Create a simple calculator:

Create calculator.js:

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

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

// Your code: call these functions and print results

5. Create a Hello World server:

Create server.js:

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200);
  res.end("Hello, World!");
});

server.listen(3000);
console.log("Server running on http://localhost:3000");

Run it and visit http://localhost:3000 in your browser.

6. Extend the server:

Add more routes to your server:

  • / → "Home page"
  • /about → "About page"
  • /contact → "Contact page"
  • anything else → "Page not found"

Common Mistakes

Mistake 1: Forgetting to Install Node.js

You: node hello.js
Terminal: command not found

Solution: Install Node.js from nodejs.org

Mistake 2: Running a File That Doesn't Exist

node nonexistent.js
# Error: Cannot find module 'nonexistent.js'

Check the filename is correct and you're in the right folder.

Mistake 3: Forgetting to Save the File

// You write this in the editor
console.log("Hello");

// But don't save it
node hello.js
// Node runs the old version (or no file found)

Always save before running.

Mistake 4: Not Stopping the Server Before Restarting

node server.js
# (ctrl + C to stop)

node server.js
# If you don't stop first:
# Error: Port 3000 already in use

Stop with Ctrl + C before running again.

Mistake 5: Typos in require()

const http = require("htttp");  // WRONG
const http = require("http");   // RIGHT

The module name is case-sensitive.


Next Steps

You've learned the basics. Here's what to explore next:

Learn More JavaScript

  • Variables and data types
  • Functions and callbacks
  • Objects and arrays
  • ES6+ features

Learn Node.js Modules

  • fs module (file operations)
  • path module (file paths)
  • events module (event handling)
  • stream module (data streaming)

Learn npm and Packages

  • Install packages: npm install
  • Use package.json
  • Manage dependencies
  • Use popular packages

Learn a Framework

  • Express.js - Web framework
  • Fastify - Fast web framework
  • Hapi - Full-featured framework

Build Projects

  • Web server
  • API
  • Command-line tool
  • Real-time application

Quick Recap

  • Node.js is a JavaScript runtime for servers and computers.

  • Installation is simple - download from nodejs.org and run the installer.

  • REPL is an interactive JavaScript shell. Type node to start it.

  • Scripts are JavaScript files you run with node filename.js.

  • Server listens for requests and sends responses.

  • Port 3000 is a common port for development (http://localhost:3000).

  • Ctrl + C stops a running script (like a server).

  • File structure matters. Organize your code as projects grow.

  • console.log() prints to the terminal.

  • require() imports modules (like http).

You now have Node.js running. You can execute JavaScript anywhere. The world of back-end development is open.

Build something! 🚀


If you enjoyed this article, check out my other blogs on this profile. 🔗 Connect with me: LinkedIn | GitHub | X (Twitter)