Skip to main content

Command Palette

Search for a command to run...

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

Updated
37 min read
Setting Up Your First Node.js Application Step-by-Step

1. Installing Node.js

Introduction

In the modern world of web development, running JavaScript outside the browser has become essential. Whether you're building a web server, automating tasks, or creating command-line tools, you need a runtime environment that can execute JavaScript on your machine. Node.js is exactly that — a powerful, open-source JavaScript runtime that has transformed how developers build applications. This article walks you through installing Node.js, understanding its core concepts, and running your very first script.


Definition

Node.js is an open-source, cross-platform runtime environment that allows JavaScript code to be executed outside of a web browser. It is built on Chrome's V8 JavaScript engine — the same engine that powers Google Chrome — and enables developers to use JavaScript for server-side programming, scripting, and general-purpose computing.

In simple terms:

Node.js = JavaScript + the ability to run on your computer (not just in a browser)

Explanation

How Node.js Works

When you write JavaScript in a browser, the browser's engine reads and runs it. Node.js brings that same capability to your operating system. It takes your .js file, passes it through the V8 engine, and produces an output — all without needing a browser.

Here is the basic execution flow:

Your Script (.js file)
        ↓
   Node.js Runtime
        ↓
  V8 JavaScript Engine
        ↓
  Operating System
        ↓
     Output / Result

Installing Node.js (OS-Neutral Steps)

  1. Visit the official website: https://nodejs.org

  2. Download the LTS (Long Term Support) version — recommended for most users

  3. Run the installer for your operating system (Windows, macOS, or Linux)

  4. Follow the on-screen instructions

  5. Verify installation by opening your terminal or command prompt and typing:

node --version
npm --version

If both commands return version numbers, Node.js is successfully installed.

What is the REPL?

Before writing full scripts, it helps to understand the REPL.

REPL stands for:

  • Read — reads the input you type

  • Evaluate — evaluates (runs) the code

  • Print — prints the result

  • Loop — loops back and waits for the next input

Think of the REPL as an interactive playground where you can type JavaScript one line at a time and instantly see the result. You launch it simply by typing node in your terminal with no file name.

node

You will see a > prompt — that means Node.js is ready to accept your code.

Example

Example 1 — Using the REPL

Open your terminal and type node, then enter:

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

> 5 + 10
15

> "Node".toUpperCase()
'NODE'

Each line is read, evaluated, printed, and the loop continues waiting for more input. Press Ctrl + C twice to exit.

Example 2 — Running Your First Script

Step 1: Create a file called hello.js and write this inside it:

console.log("Node.js is running!");
console.log("2 + 3 =", 2 + 3);

Step 2: Open your terminal, navigate to the folder where the file is saved, and run:

node hello.js

Output:

Node.js is running!
2 + 3 = 5

That's it — you've just executed your first Node.js script!

Script → Runtime → Output Flow

┌─────────────────┐
│   hello.js      │  ← You write this
│  (your script)  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Node.js        │  ← Reads and processes your file
│  Runtime        │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  V8 Engine      │  ← Compiles JavaScript to machine code
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Terminal       │  ← Displays the result
│  Output         │
└─────────────────┘

Conclusion

Node.js has made JavaScript a truly versatile language — no longer limited to browsers, but capable of running anywhere. In this article, we covered what Node.js is, how to install it in an OS-neutral way, what the REPL is and how to use it interactively, and how to write and execute your very first script. This is just the beginning. With Node.js installed and working on your machine, you now have the foundation to explore file handling, building servers, working with APIs, and much more — all using the JavaScript you already know.


2. Checking installation using terminal

Introduction

Once you have installed Node.js on your machine, the very next step is to verify that the installation was successful. Many beginners skip this step and run into confusing errors later. The terminal is your most reliable tool for confirming that Node.js is properly set up and ready to use. This article explains how to check your Node.js installation using simple terminal commands, what the results mean, and how to take your first steps inside the Node.js environment — all in an OS-neutral way that works on Windows, macOS, and Linux.


Definition

Checking the installation means using your system's terminal (also called the command prompt, shell, or console) to confirm that Node.js and its companion tool npm (Node Package Manager) are correctly installed and accessible from anywhere on your machine.

A successful installation check means your system recognizes the node and npm commands and returns valid version numbers.

Terminal — A text-based interface where you type commands and receive text output from the operating system.

npm — A tool that comes bundled with Node.js and is used to install and manage JavaScript packages and libraries.

Explanation

Step 1 — Open Your Terminal

Operating System How to Open Terminal
Windows Press Win + R, type cmd or powershell, press Enter
macOS Press Cmd + Space, type Terminal, press Enter
Linux Press Ctrl + Alt + T or search for Terminal in apps

All commands from this point are the same across all platforms.

Step 2 — Check Node.js Version

Type the following command and press Enter:

node --version

or the shorthand:

node -v

Expected Output:

v20.11.0

(Your version number may differ depending on what you installed)

If you see a version number starting with v, Node.js is correctly installed.

Step 3 — Check npm Version

npm is automatically installed alongside Node.js. Verify it with:

npm --version

or:

npm -v

Expected Output:

10.2.4

Step 4 — Check Installation Location (Optional but Useful)

To see exactly where Node.js is installed on your system:

bash

node --help

Or to find the file path of the node executable:

which node

(macOS / Linux)

where node

(Windows)

Example Output:

/usr/local/bin/node        ← macOS / Linux
C:\Program Files\nodejs\node.exe  ← Windows

What the Version Check Flow Looks Like

You type: node --version
          ↓
Terminal sends command to OS
          ↓
OS looks for 'node' in system PATH
          ↓
Finds Node.js installation
          ↓
Node.js returns its version number
          ↓
Terminal prints: v20.11.0

What is the REPL?

Before moving beyond version checks, it is worth knowing about the REPL — because it is the simplest way to confirm Node.js is not just installed, but actually working and executing code.

REPL stands for:

Letter Meaning What it does
R Read Reads the JavaScript you type
E Evaluate Runs the code immediately
P Print Prints the result to the screen
L Loop Loops back and waits for the next input

Think of the REPL as a live JavaScript scratch pad built directly into your terminal.

Launching the REPL

Simply type:

node

You will see a prompt like this:

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

The > symbol means Node.js is ready and listening. You are now inside the REPL.

Example

Example 1 — Full Installation Check in Terminal

$ node --version
v20.11.0

$ npm --version
10.2.4

Both commands returned version numbers — installation is confirmed and working

Example 2 — Confirming Node.js Actually Runs Code via REPL

After typing node to enter the REPL:

> console.log("Node.js is working!")
Node.js is working!

> 10 * 5
50

> typeof "hello"
'string'

Each line is instantly evaluated and the result is printed. This confirms Node.js is not just installed, but fully functional.

To exit the REPL, press Ctrl + C twice, or type:

> .exit

Example 3 — What an Error Looks Like (If Not Installed)

If Node.js is not installed or not found in the system PATH, you will see:

$ node --version
'node' is not recognized as an internal or external command   ← Windows

command not found: node    ← macOS / Linux

This means either Node.js was not installed, or the system PATH was not updated during installation. The fix is to reinstall from https://nodejs.org and restart your terminal.

Complete Verification Flow Diagram

┌──────────────────────────┐
│   Open Terminal          │  ← cmd / powershell / bash
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│   node --version         │  ← Check Node.js
│   Output: v20.11.0  ✓   │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│   npm --version          │  ← Check npm
│   Output: 10.2.4    ✓   │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│   type: node             │  ← Launch REPL
│   Output: >         ✓   │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│  console.log("test")     │  ← Run test code
│  Output: test       ✓   │
└──────────────────────────┘
        Installation Verified!

Conclusion

Verifying your Node.js installation is a small but critical step that saves you from debugging errors down the line. In this article, we covered how to open the terminal on any operating system, use node --version and npm --version to confirm successful installation, understand what the REPL is and how to use it as a live verification tool, and recognize what error messages look like when something goes wrong. With a verified installation, you can now confidently move forward — writing scripts, running files, and exploring everything Node.js has to offer.


3. Understanding Node REPL

Introduction

When you start learning Node.js, you do not always need to create a file and run a full script just to test a single line of code. Node.js comes with a built-in interactive environment that lets you write and run JavaScript instantly, one line at a time, directly in your terminal. This environment is called the REPL. It is one of the most useful tools for beginners and experienced developers alike — perfect for experimenting, debugging small pieces of logic, and exploring how JavaScript behaves in the Node.js runtime. This article explains what the REPL is, how it works, and how to use it effectively.


Definition

REPL stands for Read, Evaluate, Print, Loop — an interactive programming environment in Node.js that processes JavaScript input line by line and instantly displays the result.

Letter Word Meaning
R Read Reads the JavaScript code you type
E Evaluate Executes and evaluates the code
P Print Prints the result to the screen
L Loop Loops back and waits for the next input

Think of the REPL as a live conversation between you and Node.js — you type something, and it responds instantly.

The REPL is not a file, not a framework, and not a separate tool — it is built directly into Node.js and available the moment Node.js is installed.

Explanation

How to Launch the REPL

Open your terminal (on any operating system) and simply type:

node

Press Enter. You will see something like this:

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

The > symbol is the REPL prompt — it means Node.js is ready and waiting for your input.

How the REPL Works — Step by Step

Every time you type a line and press Enter, the REPL follows this exact cycle:

┌─────────────────────────────┐
│        You Type Code        │  ← e.g., 2 + 3
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│     R — READ                │  ← REPL reads your input
│  Parses the JavaScript      │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│     E — EVALUATE            │  ← V8 engine runs the code
│  Executes in Node.js        │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│     P — PRINT               │  ← Result is shown on screen
│  Output: 5                  │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│     L — LOOP                │  ← Waits for next input
│  Prompt returns: >          │
└─────────────────────────────┘

This cycle repeats every single time you press Enter.

REPL Special Commands

The REPL has its own set of dot-commands for controlling the session:

Command What it Does
.help Shows all available REPL commands
.exit Exits the REPL session
.clear Clears the current session context
.save filename.js Saves your session history to a file
.load filename.js Loads and runs a file inside the REPL

REPL Key Shortcuts

Shortcut Action
Ctrl + C (once) Cancels current input line
Ctrl + C (twice) Exits the REPL completely
Ctrl + D Exits the REPL completely
↑ / ↓ arrow keys Navigate through command history
Tab Auto-completes variable or method names

Variables and Memory in REPL

The REPL remembers variables within the same session. You can declare a variable on one line and use it on the next:

> let name = "Node.js"
undefined
> name
'Node.js'
> name.toUpperCase()
'NODE.JS'

Note: undefined appears after let name = "Node.js" because assignment statements do not return a value — this is completely normal behavior.

Multi-line Code in REPL

The REPL supports multi-line input. When you open a block with {, it automatically waits for you to close it:

> function greet(name) {
... console.log("Hello, " + name)
... }
undefined
> greet("World")
Hello, World

The ... prompt means the REPL knows your code is not finished yet and is waiting for more input.

The REPL Execution Flow Inside Node.js

┌──────────────────────────────────────┐
│          Terminal / Shell            │
│  You type JavaScript at > prompt     │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│          Node.js REPL Layer          │
│  Reads input → wraps in context      │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│          V8 JavaScript Engine        │
│  Compiles and executes the code      │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│          Output Printed              │
│  Result shown at > prompt            │
└──────────────────────────────────────┘
                  │
                  ▼
         Loop restarts → >

Example

Example 1 — First Execution in the REPL

Launch the REPL by typing node in your terminal, then try these:

> console.log("Hello from REPL!")
Hello from REPL!
undefined

> 100 / 4
25

> "Node".repeat(3)
'NodeNodeNode'

Each result is printed immediately after pressing Enter.

Example 2 — Using Variables Across Lines

> let x = 10
undefined

> let y = 20
undefined

> x + y
30

> let result = x * y
undefined

> console.log("Result is:", result)
Result is: 200

The REPL holds all variables in memory for the entire session.

Example 3 — Writing a Function and Calling It

> function square(n) {
...   return n * n
... }
undefined

> square(5)
25

> square(12)
144

Example 4 — Using Built-in JavaScript Objects

> Math.PI
3.141592653589793

> Math.sqrt(144)
12

> Date()
'Wed Apr 22 2026 10:30:00 GMT+0000'

> typeof 42
'number'

> Array.isArray([1, 2, 3])
true

Example 5 — Saving a Session to a File

> let a = 5
> let b = 10
> console.log(a + b)
15
> .save mysession.js
Session saved to: mysession.js

This saves everything you typed into a .js file that you can run later with node mysession.js.

Complete REPL Session Flow Diagram

┌─────────────────────────────────────┐
│  Open Terminal                      │
│  Type: node → Press Enter           │
└──────────────────┬──────────────────┘
                   │
                   ▼
┌─────────────────────────────────────┐
│  REPL Starts                        │
│  Prompt appears: >                  │
└──────────────────┬──────────────────┘
                   │
         ┌─────────┴──────────┐
         ▼                    ▼
┌─────────────────┐  ┌─────────────────────┐
│ Single-line     │  │ Multi-line           │
│ > 2 + 2         │  │ > function add() {   │
│ Output: 4       │  │ ...  return 1        │
└────────┬────────┘  │ ... }                │
         │           └──────────┬──────────┘
         └──────────┬───────────┘
                    ▼
┌─────────────────────────────────────┐
│  Result Printed                     │
│  REPL Loops back to > prompt        │
└──────────────────┬──────────────────┘
                   │
                   ▼
┌─────────────────────────────────────┐
│  Exit with Ctrl+C twice or .exit    │
└─────────────────────────────────────┘

Conclusion

The Node.js REPL is one of the most accessible and powerful tools available to any JavaScript developer. It requires no setup, no files, and no frameworks — just Node.js and your terminal. In this article, we covered what REPL means and how each letter describes a step in the cycle, how to launch and exit the REPL, how variables and functions persist across lines within a session, how to use special dot-commands and keyboard shortcuts, and how the REPL connects to the V8 engine to execute your code. Mastering the REPL gives you a fast, friction-free way to experiment with JavaScript, test ideas instantly, and deepen your understanding of how Node.js works under the hood.


4. Creating first JS file

Introduction

While the REPL is excellent for quick experiments and testing small pieces of code, real programs need to be saved, organized, and reused. That is where JavaScript files come in. Creating your first .js file is the moment you step from interactive experimentation into actual programming. It is a simple but significant milestone — you write your code, save it to a file, and tell Node.js to run it. This article walks you through creating your first JavaScript file from scratch, understanding how Node.js processes it, and seeing your output clearly in the terminal, all without using any frameworks or external tools.


Definition

A JavaScript file is a plain text file with a .js extension that contains JavaScript code. Instead of typing code line by line in the REPL, you write all your instructions inside this file and run the entire file at once using Node.js.

Term Meaning
.js file A file containing JavaScript code, saved with the .js extension
node command The terminal command used to execute a .js file using Node.js
Entry point The file Node.js starts reading and executing from the top
console.log() A built-in JavaScript function that prints output to the terminal

A .js file is to Node.js what a recipe is to a chef — it contains all the instructions that need to be followed, in order, from top to bottom.

Explanation

Step 1 — Choose a Location for Your File

Before creating a file, decide where to save it. It is good practice to create a dedicated folder for your Node.js projects.

Open your terminal and create a new folder:

mkdir my-first-node-app

Navigate into it:

cd my-first-node-app

This works the same way on Windows, macOS, and Linux.

Step 2 — Create Your JavaScript File

You can create a .js file using any plain text editor. Choose whichever suits you:

Tool Type Platform
VS Code Code editor Windows, macOS, Linux
Notepad Basic text editor Windows
TextEdit Basic text editor macOS
Nano / Vim Terminal editor macOS, Linux
Gedit Text editor Linux

Create a file named app.js in your folder. The name app.js is a widely used convention for the main entry point of a Node.js program.

To create the file directly from the terminal:


# macOS / Linux
touch app.js

# Windows (Command Prompt)
type nul > app.js

# Windows (PowerShell)
New-Item app.js

Step 3 — Write Your Code

Open app.js in your text editor and write your first JavaScript code:

console.log("Hello, Node.js!");
console.log("My first JavaScript file is running.");

Save the file after writing.

Step 4 — Run the File with Node.js

Go back to your terminal, make sure you are inside the folder where app.js is saved, and run:

node app.js

Node.js will read the file from top to bottom and execute every line.

How Node.js Reads and Runs Your File

When you type node app.js, here is exactly what happens internally:

┌──────────────────────────────────┐
│  You type: node app.js           │
│  and press Enter                 │
└─────────────────┬────────────────┘
                  │
                  ▼
┌──────────────────────────────────┐
│  Node.js Runtime                 │
│  Locates app.js on your system   │
└─────────────────┬────────────────┘
                  │
                  ▼
┌──────────────────────────────────┐
│  File is Read                    │
│  Code is loaded into memory      │
└─────────────────┬────────────────┘
                  │
                  ▼
┌──────────────────────────────────┐
│  V8 JavaScript Engine            │
│  Compiles JS to machine code     │
└─────────────────┬────────────────┘
                  │
                  ▼
┌──────────────────────────────────┐
│  Code Executes Line by Line      │
│  Top → Bottom                    │
└─────────────────┬────────────────┘
                  │
                  ▼
┌──────────────────────────────────┐
│  Output Printed in Terminal      │
└──────────────────────────────────┘

Script → Runtime → Output Flow

┌──────────────────┐
│    app.js        │  ← Your JavaScript file
│                  │
│ console.log(..)  │
│ console.log(..)  │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│  Node.js         │  ← Receives the file
│  Runtime         │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│  V8 Engine       │  ← Compiles and executes
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│  Terminal        │  ← Displays final output
│  Output          │
└──────────────────┘

File vs REPL — Key Differences

Feature REPL JS File
How to start Type node Type node filename.js
Code saved? No — lost on exit Yes — stored permanently
Runs line by line? Yes, interactively Yes, but all at once
Good for Quick tests Real programs
Reusable? No Yes

Example

Example 1 — The Simplest First File

File: app.js

console.log("Hello, Node.js!");
console.log("My first JavaScript file is running.");

Run it:

node app.js

Output:

Hello, Node.js!
My first JavaScript file is running.

Example 2 — Using Variables and Expressions

File: app.js

let firstName = "Ada";
let lastName = "Lovelace";
let fullName = firstName + " " + lastName;

console.log("Name:", fullName);
console.log("Name length:", fullName.length);

Output:

Name: Ada Lovelace
Name length: 12

Example 3 — Using a Function

File: app.js

function greet(name) {
  console.log("Welcome to Node.js, " + name + "!");
}

greet("Alice");
greet("Bob");
greet("Charlie");

Output:

Welcome to Node.js, Alice!
Welcome to Node.js, Bob!
Welcome to Node.js, Charlie!

Example 4 — Simple Calculation Program

File: app.js

let price = 100;
let taxRate = 0.18;
let tax = price * taxRate;
let total = price + tax;

console.log("Price:     $" + price);
console.log("Tax (18%): $" + tax);
console.log("Total:     $" + total);

Output:

Price:     $100
Tax (18%): $18
Total:     $118

Example 5 — Code Runs Top to Bottom

File: app.js

console.log("Step 1 — Program starts");

let x = 50;
console.log("Step 2 — Variable x is set to", x);

x = x * 2;
console.log("Step 3 — x doubled is now", x);

console.log("Step 4 — Program ends");

Output:

Step 1 — Program starts
Step 2 — Variable x is set to 50
Step 3 — x doubled is now 100
Step 4 — Program ends

This demonstrates clearly that Node.js reads and executes your file strictly from top to bottom, one line at a time.

Complete File Creation and Execution Flow

┌─────────────────────────────────────────┐
│  Step 1: Create folder                  │
│  mkdir my-first-node-app                │
│  cd my-first-node-app                   │
└────────────────────┬────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────┐
│  Step 2: Create file                    │
│  touch app.js  (or use text editor)     │
└────────────────────┬────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────┐
│  Step 3: Write code inside app.js       │
│  console.log("Hello, Node.js!")         │
└────────────────────┬────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────┐
│  Step 4: Run the file                   │
│  node app.js                            │
└────────────────────┬────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────┐
│  Output appears in terminal             │
│  Hello, Node.js!                   ✓   │
└─────────────────────────────────────────┘

Conclusion

Creating your first JavaScript file is the foundation of everything you will build with Node.js. In this article, we covered how to create a project folder, how to create a .js file using any text editor on any operating system, how to write JavaScript code inside the file, how to run it using the node command, and how Node.js processes your file from top to bottom through the V8 engine. Unlike the REPL which is temporary and interactive, a JavaScript file is permanent, reusable, and scalable. Every Node.js application — no matter how large or complex — begins exactly the way yours did: with a single file, a few lines of code, and one command in the terminal.


5. Running script using node command

Introduction

Writing JavaScript code inside a file is only half the job. The other half is telling Node.js to run it. That is exactly what the node command does. It is the single most important command you will use in Node.js development — a direct instruction to the Node.js runtime to pick up your file, process it through the V8 engine, and deliver the output to your terminal. Whether you are running a simple two-line script or a complex multi-file program, it always starts with the same thing: typing node followed by your filename. This article explains exactly how that works, what happens behind the scenes, and how to run your scripts confidently on any operating system.


Definition

The node command is a terminal instruction that launches the Node.js runtime and tells it to execute a specific JavaScript file. It is the bridge between your written code and its actual execution on your machine.

Term Meaning
node The command that starts the Node.js runtime
script A .js file containing JavaScript instructions
runtime The environment that reads, compiles, and runs your code
execution The process of Node.js carrying out the instructions in your file
output The result printed to the terminal after the script runs

Basic Syntax:

node filename.js

Think of the node command as pressing the play button on your code — it tells Node.js to start from the top of your file and run every instruction until it reaches the end.

Explanation

How the Node Command Works

When you type node app.js and press Enter, a precise sequence of events takes place inside your system. Understanding this sequence helps you write better code and debug problems faster.

┌──────────────────────────────────────┐
│  Terminal                            │
│  You type: node app.js               │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│  Operating System                    │
│  Looks for 'node' in system PATH     │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│  Node.js Runtime Starts              │
│  Locates and opens app.js            │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│  File is Read into Memory            │
│  Code is parsed for syntax errors    │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│  V8 JavaScript Engine                │
│  Compiles JavaScript to machine code │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│  Code Executes Line by Line          │
│  Top → Bottom                        │
└─────────────────┬────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────┐
│  Output Printed in Terminal          │
│  Program exits cleanly               │
└──────────────────────────────────────┘

Step-by-Step — Running Your First Script

Step 1 — Create your JavaScript file

Create a file named app.js and write some code inside it:

console.log("Script is running!");

Step 2 — Open your terminal

Operating System Terminal to Use
Windows Command Prompt or PowerShell
macOS Terminal
Linux Terminal or Shell

Step 3 — Navigate to your file's folder

bash

cd path/to/your/folder

Step 4 — Run the script

node app.js

Step 5 — See the output

Script is running!

That is the complete cycle — from file to output.

Running Scripts from Different Locations

You do not always have to navigate into the folder first. You can pass the full path to the file directly:

# macOS / Linux
node /home/user/projects/app.js

# Windows
node C:\Users\user\projects\app.js

Or a relative path from where you currently are:

node ./projects/app.js

Common node Command Variations

Command What it Does
node app.js Runs the file named app.js
node index.js Runs the file named index.js
node ./folder/app.js Runs app.js inside a subfolder
node . Runs the main file defined in package.json
node --version Prints the installed Node.js version
node Opens the REPL (no file specified)

What is the REPL — and How is it Different?

When you type node without a filename, Node.js does not look for a file. Instead it opens the REPL — an interactive environment where you type code one line at a time.

REPL stands for Read, Evaluate, Print, Loop:

Letter Word Action
R Read Reads each line you type
E Evaluate Executes it immediately
P Print Prints the result
L Loop Waits for the next line
node          ← opens REPL (no file)
node app.js   ← runs a file (no REPL)

The REPL is useful for quick tests, but running a file with node filename.js is how real programs are executed.

Script → Runtime → Output Flow

┌─────────────────────┐
│     app.js          │  ← Your script (plain .js file)
│                     │
│  console.log(...)   │
│  let x = 10         │
│  console.log(x)     │
└──────────┬──────────┘
           │  node app.js
           ▼
┌─────────────────────┐
│   Node.js Runtime   │  ← Receives and loads your file
│                     │
│  Reads the file     │
│  Checks for errors  │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│   V8 Engine         │  ← Compiles and executes
│                     │
│  JS → Machine Code  │
│  Runs each line     │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│   Terminal Output   │  ← Result appears here
│                     │
│  Script is running! │
│  10                 │
└─────────────────────┘

Understanding Errors When Running Scripts

If something is wrong in your file, Node.js will stop and print an error message instead of output. There are two main types:

Syntax Error — code is written incorrectly:

javascript

// app.js
console.log("Hello"
$ node app.js
SyntaxError: Unexpected end of input

Runtime Error — code is valid but fails during execution:

// app.js
console.log(myVariable); 
$ node app.js
ReferenceError: myVariable is not defined

Both errors tell you the type of error and the line number — use these clues to find and fix the problem quickly.

Example

Example 1 — First Script Execution

File: app.js

console.log("Hello, Node.js!");
console.log("The node command is working.");

Run:

node app.js

Output:

Hello, Node.js!
The node command is working.

Example 2 — Running a Script with Variables

File: app.js

let language = "JavaScript";
let runtime = "Node.js";

console.log("Language:", language);
console.log("Runtime:", runtime);
console.log(language + " runs on " + runtime);

Run:

node app.js

Output:

Language: JavaScript
Runtime: Node.js
JavaScript runs on Node.js

Example 3 — Running a Script with a Function

File: app.js

function calculateArea(width, height) {
  return width * height;
}

let area = calculateArea(8, 5);
console.log("Area of rectangle:", area);

Run:

node app.js

Output:

Area of rectangle: 40

Example 4 — Running a Script with a Loop

File: app.js

console.log("Counting from 1 to 5:");

for (let i = 1; i <= 5; i++) {
  console.log("Count:", i);
}

console.log("Loop complete.");

Run:

node app.js

Output:

Counting from 1 to 5:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop complete.

Example 5 — Running Scripts from a Subfolder

Suppose your folder structure looks like this:

my-project/
└── scripts/
    └── app.js

From inside my-project, you can run:

node scripts/app.js

Output:

Hello from a subfolder script!

Node.js handles the path and runs the file correctly regardless of how deeply nested it is.

Complete Run Flow Diagram — From Command to Output

┌──────────────────────────────────────────────┐
│  You open the terminal                       │
└─────────────────────┬────────────────────────┘
                      │
                      ▼
┌──────────────────────────────────────────────┐
│  Navigate to project folder                  │
│  cd my-first-node-app                        │
└─────────────────────┬────────────────────────┘
                      │
                      ▼
┌──────────────────────────────────────────────┐
│  Type the node command                       │
│  node app.js                                 │
└─────────────────────┬────────────────────────┘
                      │
                      ▼
┌──────────────────────────────────────────────┐
│  Node.js Runtime activates                   │
│  Finds and reads app.js                      │
└─────────────────────┬────────────────────────┘
                      │
                      ▼
┌──────────────────────────────────────────────┐
│  V8 Engine compiles and runs the code        │
│  Line by line, top to bottom                 │
└─────────────────────┬────────────────────────┘
                      │
                      ▼
┌──────────────────────────────────────────────┐
│  Output is printed in the terminal      ✓   │
│  Program exits cleanly                       │
└──────────────────────────────────────────────┘

Conclusion

The node command is the starting point of every Node.js program. It is simple in syntax but powerful in what it triggers — from locating your file, to compiling it through the V8 engine, to delivering the final output in your terminal. In this article, we covered the exact syntax of the node command, what happens step by step when you run a script, how to run files from the same folder or different paths, the difference between running a file and opening the REPL, and how to read error messages when something goes wrong. Every Node.js developer — regardless of experience level — uses this command dozens of times a day. Mastering it early gives you a solid and confident foundation for everything that comes next.


6. Writing Hello World server

Introduction

Up until now, you have been writing scripts that run, print output, and exit. But one of the most powerful things Node.js can do is something fundamentally different — it can keep running and listen for incoming requests. This is the foundation of every web server, API, and backend application on the internet. Writing a Hello World server is the moment your Node.js journey shifts from running scripts to building networked applications. It requires no frameworks, no external packages, and no complex setup — just Node.js and one built-in module called http. This article walks you through writing, understanding, and running your very first Node.js web server from scratch.


Definition

A web server is a program that runs continuously, listens for incoming requests over a network, and sends back responses. In Node.js, a server is created using the built-in http module — a core part of Node.js that handles the communication between a browser or client and your program.

Term Meaning
http module A built-in Node.js module for creating web servers and handling network requests
server A program that listens for requests and sends back responses
port A numbered channel on your computer through which network traffic flows
request (req) The incoming message sent by a browser or client to the server
response (res) The reply your server sends back to the client
localhost A special address that refers to your own computer (127.0.0.1)

Think of a server as a restaurant. The client is the customer, the request is the order, and the response is the food that comes back. The server stays open and keeps serving as long as it is running.

Explanation

The http Module

Node.js comes with a set of built-in core modules that you can use without installing anything. The http module is one of the most important — it gives you everything you need to create a server that communicates over the web.

You bring it into your file using require:

const http = require('http');

No installation needed. No npm install. It is already part of Node.js.

How a Node.js Server Works

When you create a server with Node.js, here is what happens in sequence:

┌──────────────────────────────────────────┐
│  Your Script (server.js)                 │
│  Creates a server using http module      │
└─────────────────┬────────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────────┐
│  Node.js Runtime                         │
│  Starts and keeps the process alive      │
└─────────────────┬────────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────────┐
│  Server binds to a Port                  │
│  Listens for incoming connections        │
└─────────────────┬────────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────────┐
│  Browser sends a Request                 │
│  e.g. visit http://localhost:3000        │
└─────────────────┬────────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────────┐
│  Server receives Request                 │
│  Runs your callback function             │
└─────────────────┬────────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────────┐
│  Server sends back a Response            │
│  "Hello, World!"                         │
└─────────────────┬────────────────────────┘
                  │
                  ▼
┌──────────────────────────────────────────┐
│  Browser displays the Response           │
│  Server loops back and keeps listening   │
└──────────────────────────────────────────┘

Key Parts of a Node.js Server

Every Hello World server in Node.js has three essential parts:

1. Creating the server

const server = http.createServer(function(req, res) {
  // handle request and send response here
});

The function inside createServer is called automatically every time a request comes in. It receives two objects — req (the request) and res (the response).

2. Writing and ending the response

res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');

writeHead sets the status code and headers. Status code 200 means everything is OK. res.end() sends the response body and signals that the response is complete.
3. Listening on a port

server.listen(3000, function() {
  console.log('Server is running on http://localhost:3000');
});

This tells the server which port to listen on. Port 3000 is a common choice for local development. Once this runs, the server stays alive and waits.

What is a Port?

Your computer has thousands of numbered ports — think of them as doors through which different programs communicate. When your server listens on port 3000, it is opening door number 3000 and waiting for anyone who knocks.

Your Computer
┌──────────────────────────────────┐
│  Port 80   → HTTP (web)          │
│  Port 443  → HTTPS (secure web)  │
│  Port 3000 → Your Node.js server │
│  Port 5000 → Another app         │
└──────────────────────────────────┘

When you visit http://localhost:3000 in your browser, you are knocking on door 3000 of your own machine.

Script → Runtime → Output Flow

┌─────────────────────────┐
│      server.js          │  ← Your script
│                         │
│  require('http')        │
│  createServer(...)      │
│  server.listen(3000)    │
└───────────┬─────────────┘
            │  node server.js
            ▼
┌─────────────────────────┐
│   Node.js Runtime       │  ← Loads and runs the file
│                         │
│  Keeps process alive    │
│  Opens port 3000        │
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│   V8 Engine             │  ← Compiles and executes
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│   Server Running        │  ← Stays alive, listens
│   localhost:3000        │
└───────────┬─────────────┘
            │  Browser visits URL
            ▼
┌─────────────────────────┐
│   Response Sent         │  ← "Hello, World!"
│   Browser displays it   │
└─────────────────────────┘

How to Stop the Server

Unlike regular scripts that exit on their own, a server runs forever until you stop it manually. To stop it, go to your terminal and press:

Ctrl + C

This sends an interrupt signal to Node.js and shuts the server down cleanly.

Example

Example 1 — The Simplest Hello World Server

File: server.js

const http = require('http');

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

server.listen(3000, function() {
  console.log('Server is running on http://localhost:3000');
});

Run it:

node server.js

Terminal Output:

Server is running on http://localhost:3000

Now open your browser and visit:

http://localhost:3000

Browser displays:

Hello, World!

Your first server is live and responding.

Example 2 — Server with a Personalized Message

File: server.js

const http = require('http');

const server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Welcome to my first Node.js server!\nBuilt without any frameworks.');
});

server.listen(3000, function() {
  console.log('Server started on http://localhost:3000');
});

Browser displays:

Welcome to my first Node.js server!
Built without any frameworks.

Example 3 — Server that Returns HTML

File: server.js

const http = require('http');

const server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<h1>Hello, World!</h1><p>This is my Node.js server.</p>');
});

server.listen(3000, function() {
  console.log('Server running on http://localhost:3000');
});

By changing Content-Type to text/html, the browser now renders the HTML instead of displaying it as plain text.

Browser displays:

Hello, World!

This is my Node.js server.

Example 4 — Server that Logs Every Request

File: server.js

const http = require('http');

const server = http.createServer(function(req, res) {
  console.log('Request received:', req.method, req.url);

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!');
});

server.listen(3000, function() {
  console.log('Server running on http://localhost:3000');
});

Terminal output every time someone visits the server:

Server running on http://localhost:3000
Request received: GET /
Request received: GET /favicon.ico

This shows you the method (GET) and the URL path (/) of every request the server receives — useful for understanding how browsers communicate with servers.

Example 5 — Server with Request Count

File: server.js

const http = require('http');

let requestCount = 0;

const server = http.createServer(function(req, res) {
  requestCount++;
  console.log('Total requests so far:', requestCount);

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World! This is request number ' + requestCount);
});

server.listen(3000, function() {
  console.log('Server running on http://localhost:3000');
});

Each time you refresh the browser:

Hello, World! This is request number 1
Hello, World! This is request number 2
Hello, World! This is request number 3

This demonstrates that the server stays alive between requests and can maintain state — something a regular script cannot do.

Complete Server Lifecycle Diagram

┌──────────────────────────────────────────────────┐
│  Write server.js                                 │
│  require http → createServer → listen(3000)      │
└──────────────────────┬───────────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────────┐
│  Run: node server.js                             │
│  Terminal prints: Server running on port 3000    │
└──────────────────────┬───────────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────────┐
│  Server is LIVE — stays alive, waits for request │
└──────────────────────┬───────────────────────────┘
                       │
          ┌────────────┴────────────┐
          ▼                         ▼
┌──────────────────┐     ┌──────────────────────┐
│ Browser visits   │     │ No request yet        │
│ localhost:3000   │     │ Server keeps waiting  │
└────────┬─────────┘     └──────────────────────┘
         │
         ▼
┌──────────────────────────────────────────────────┐
│  Server receives request                         │
│  Runs callback → writes response → res.end()     │
└──────────────────────┬───────────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────────┐
│  Browser displays: Hello, World!            ✓   │
│  Server loops back and keeps listening           │
└──────────────────────────────────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────────┐
│  Press Ctrl + C to stop the server               │
└──────────────────────────────────────────────────┘

Conclusion

Writing a Hello World server is one of the most important milestones in learning Node.js. In this article, we covered what a web server is and how it differs from a regular script, how the built-in http module works without any external packages, the three core parts of every Node.js server — creating, responding, and listening, what ports are and how localhost connects your browser to your running server, and how the server stays alive between requests and handles each one with a callback. This single file — just a few lines of pure Node.js — contains the same fundamental ideas that power real-world APIs and backend systems. Everything more advanced you build from here is simply an extension of exactly what you wrote today.

1 views