DEV Community

Cover image for Setting Up Your First Node.js Application Step-by-Step
Pratham
Pratham

Posted on

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

From zero to "Hello World" server — no frameworks, no magic, just pure Node.js.


There's a special kind of excitement the first time you run node app.js and see your own server respond in the browser. No HTML file opened locally. No browser extension. An actual server, running on your machine, responding to HTTP requests — and you built it.

That moment happened for me early in the ChaiCode Web Dev Cohort 2026, and it's when Node.js stopped being a concept and became something real. The entire setup takes about 10 minutes, and by the end of this article, you'll have a working Node.js application running on your machine.

Let's go from zero to server, step by step.


Step 1: Installing Node.js

Node.js doesn't come pre-installed on most systems. You need to download and install it.

Download

Go to the official website: https://nodejs.org

You'll see two versions:

Version What It Means Choose This If...
LTS Long Term Support — stable, tested ✅ You're learning or building
Current Latest features, may have bugs Experimenting with new APIs

Pick LTS. It's the safe, reliable choice. The installer works on Windows, macOS, and Linux.

Installation

  • Windows/macOS: Download the installer, run it, click "Next" a few times. Done.
  • Linux (Ubuntu/Debian):
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
Enter fullscreen mode Exit fullscreen mode

When you install Node.js, you also get npm (Node Package Manager) automatically — it's how you install packages later.


Step 2: Checking Installation Using Terminal

Open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and run these commands:

Check Node.js Version

node -v
Enter fullscreen mode Exit fullscreen mode

Output (something like):

v20.12.2
Enter fullscreen mode Exit fullscreen mode

Check npm Version

npm -v
Enter fullscreen mode Exit fullscreen mode

Output (something like):

10.5.0
Enter fullscreen mode Exit fullscreen mode

If both commands show version numbers, you're good to go. Node.js is installed and ready.

What If It Says "Command Not Found"?

  • Restart your terminal — the installer may need a fresh terminal session
  • Restart your computer — some systems need a reboot to update the PATH
  • Re-run the installer and make sure "Add to PATH" is checked

Step 3: Understanding the Node REPL

Before creating files, let's meet the REPL — an interactive playground where you can type JavaScript and see results instantly.

What Is REPL?

REPL stands for:

R — Read      (reads your input)
E — Evaluate  (runs your code)
P — Print     (shows the result)
L — Loop      (waits for more input)
Enter fullscreen mode Exit fullscreen mode

It's like a JavaScript calculator that runs in your terminal. You type code, press Enter, and see the output immediately. No file creation needed.

Starting the REPL

node
Enter fullscreen mode Exit fullscreen mode

That's it. Just type node with no arguments. You'll see a > prompt:

Welcome to Node.js v20.12.2.
Type ".help" for more information.
>
Enter fullscreen mode Exit fullscreen mode

Try Some Code

> 2 + 2
4

> "Hello" + " " + "World"
'Hello World'

> Math.random()
0.7234567891234

> const name = "Pratham"
undefined

> `Welcome, ${name}!`
'Welcome, Pratham!'

> [1, 2, 3].map(n => n * 10)
[ 10, 20, 30 ]
Enter fullscreen mode Exit fullscreen mode

Node.js-Specific Things in REPL

> process.version
'v20.12.2'

> process.platform
'win32'   (or 'darwin' for macOS, 'linux' for Linux)

> __dirname
// (works in files, not REPL — we'll see this soon)
Enter fullscreen mode Exit fullscreen mode

Exiting the REPL

> .exit
Enter fullscreen mode Exit fullscreen mode

Or press Ctrl + C twice, or Ctrl + D once.

REPL Cheat Sheet

Command What It Does
.help Shows all REPL commands
.exit Exits the REPL
.break Exits a multi-line expression
.clear Resets the REPL context
Ctrl + C Cancel current input / exit
arrow key Cycle through command history

The REPL is great for quick experiments and testing small snippets. But for real code, you'll write files.


Step 4: Creating Your First JS File

Time to write real code in a file.

Create a Project Folder

mkdir my-first-node-app
cd my-first-node-app
Enter fullscreen mode Exit fullscreen mode

Create Your First File

Create a file called app.js in your favorite code editor (VS Code, for example) and write:

// app.js

const name = "Pratham";
const course = "Web Dev Cohort 2026";

console.log(`Hello! I'm ${name}.`);
console.log(`I'm learning Node.js in the ${course}.`);
console.log(`Running on Node.js ${process.version}`);
console.log(`Platform: ${process.platform}`);
console.log(`Current directory: ${process.cwd()}`);
Enter fullscreen mode Exit fullscreen mode

This is a regular JavaScript file — the same syntax you'd write for the browser. The difference is that it uses process, which is a Node.js global object (not available in browsers).


Step 5: Running a Script Using the node Command

Run Your File

node app.js
Enter fullscreen mode Exit fullscreen mode

Output:

Hello! I'm Pratham.
I'm learning Node.js in the Web Dev Cohort 2026.
Running on Node.js v20.12.2
Platform: win32
Current directory: C:\Users\pratham\my-first-node-app
Enter fullscreen mode Exit fullscreen mode

That's it. Your JavaScript file ran outside the browser, powered by Node.js.

Script → Runtime → Output Flow

┌──────────────────┐
│    app.js         │  ← Your JavaScript file
│                  │
│  console.log()   │
│  process.version │
│  etc.            │
└────────┬─────────┘
         │
         │  node app.js  (you run this command)
         ↓
┌──────────────────┐
│   Node.js        │  ← The runtime
│   (V8 Engine)    │
│                  │
│  Reads app.js    │
│  Compiles JS     │
│  Executes code   │
└────────┬─────────┘
         │
         ↓
┌──────────────────┐
│   Terminal        │  ← Output appears here
│                  │
│  "Hello! I'm..." │
│  "Running on..." │
│  "Platform: ..." │
└──────────────────┘
Enter fullscreen mode Exit fullscreen mode

What Node.js Globals Are Available?

In the browser, you have window, document, alert(). In Node.js, you have different globals:

Node.js Global What It Does
process Info about the current Node.js process
__dirname Absolute path of the current file's directory
__filename Absolute path of the current file
console Same as browser — log, error, warn, table
setTimeout Same as browser — schedule delayed execution
setInterval Same as browser — repeat at intervals
require() Import modules (built-in or npm packages)
module Info about the current module
exports Shortcut for module.exports

Try adding these to your app.js:

console.log("File:", __filename);
console.log("Directory:", __dirname);
console.log("Process ID:", process.pid);
console.log("Memory usage:", Math.round(process.memoryUsage().heapUsed / 1024 / 1024), "MB");
Enter fullscreen mode Exit fullscreen mode

Step 6: Writing a Hello World Server

This is the exciting part — your first HTTP server. No Express. No frameworks. Just Node.js.

Create server.js

// server.js

const http = require("http");

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

const PORT = 3000;

server.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Run It

node server.js
Enter fullscreen mode Exit fullscreen mode

Output in terminal:

Server is running at http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

Open Your Browser

Go to http://localhost:3000. You'll see:

Hello, World! This is my first Node.js server. 🚀
Enter fullscreen mode Exit fullscreen mode

You just built a web server. With JavaScript. In 10 lines of code.

How This Works — Line by Line

// 1. Import Node's built-in HTTP module
const http = require("http");

// 2. Create a server that handles every incoming request
const server = http.createServer((req, res) => {
  // req = information about the incoming request
  // res = the response we send back

  // 3. Set the status code (200 = OK) and content type
  res.writeHead(200, { "Content-Type": "text/plain" });

  // 4. Send the response body and close the connection
  res.end("Hello, World! This is my first Node.js server. 🚀");
});

// 5. Tell the server to listen on port 3000
server.listen(3000, () => {
  console.log("Server is running at http://localhost:3000");
});
Enter fullscreen mode Exit fullscreen mode

Node Execution Flow — Server

node server.js
      │
      ↓
┌────────────────────────────┐
│  Node.js loads server.js   │
│                            │
│  1. require("http")        │
│  2. createServer(handler)  │
│  3. server.listen(3000)    │
│                            │
│  Server is now LISTENING   │
│  for incoming connections  │
└────────────┬───────────────┘
             │
             │  (waiting for requests...)
             │
    Browser visits localhost:3000
             │
             ↓
┌────────────────────────────┐
│  Request arrives!          │
│                            │
│  handler(req, res) runs:   │
│  → Sets status 200         │
│  → Sends "Hello, World!"   │
│  → Connection closed       │
└────────────────────────────┘
             │
             │  (back to waiting for more requests...)
             │  Server stays running until you stop it.
Enter fullscreen mode Exit fullscreen mode

Stopping the Server

Press Ctrl + C in the terminal. The server shuts down and the terminal returns to the regular prompt.


Making the Server More Interesting

Let's upgrade from plain text to something that handles different routes:

// server.js — upgraded version

const http = require("http");

const server = http.createServer((req, res) => {
  // Set response headers
  res.writeHead(200, { "Content-Type": "text/html" });

  // Simple routing based on URL
  if (req.url === "/") {
    res.end(`
      <h1>🏠 Home Page</h1>
      <p>Welcome to my first Node.js server!</p>
      <a href="/about">About</a> | <a href="/contact">Contact</a>
    `);
  } else if (req.url === "/about") {
    res.end(`
      <h1>👤 About</h1>
      <p>I'm Pratham, a Web Dev Cohort 2026 student learning Node.js.</p>
      <a href="/">Home</a>
    `);
  } else if (req.url === "/contact") {
    res.end(`
      <h1>📧 Contact</h1>
      <p>Find me on LinkedIn or at PrathamDEV.in</p>
      <a href="/">Home</a>
    `);
  } else {
    res.writeHead(404);
    res.end(`
      <h1>404 — Page Not Found</h1>
      <p>The page "${req.url}" doesn't exist.</p>
      <a href="/">Go Home</a>
    `);
  }
});

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});
Enter fullscreen mode Exit fullscreen mode

Run it and visit:

  • http://localhost:3000/ — Home page
  • http://localhost:3000/about — About page
  • http://localhost:3000/contact — Contact page
  • http://localhost:3000/anything-else — 404 page

A multi-page web server. No framework. Just http, req.url, and res.end.


Initializing a Node.js Project with npm init

For real projects, you'll want a package.json file — it tracks your project's name, version, dependencies, and scripts.

npm init -y
Enter fullscreen mode Exit fullscreen mode

This creates a package.json:

{
  "name": "my-first-node-app",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "start": "node server.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now you can run your server with:

npm start
Enter fullscreen mode Exit fullscreen mode

This is how professional Node.js projects are structured — package.json is the backbone.


Let's Practice: Hands-On Assignment

Part 1: Explore the REPL

Open the REPL (node) and try:

> process.version
> process.platform
> process.uptime()
> os = require("os")
> os.hostname()
> os.cpus().length
> os.totalmem() / 1024 / 1024 / 1024
Enter fullscreen mode Exit fullscreen mode

Part 2: Create a Script That Reads System Info

// sysinfo.js
const os = require("os");

console.log("=== System Information ===");
console.log(`Hostname: ${os.hostname()}`);
console.log(`Platform: ${os.platform()}`);
console.log(`Architecture: ${os.arch()}`);
console.log(`CPUs: ${os.cpus().length} cores`);
console.log(`Total Memory: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log(`Free Memory: ${(os.freemem() / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log(`Uptime: ${(os.uptime() / 3600).toFixed(1)} hours`);
console.log(`Node.js: ${process.version}`);
Enter fullscreen mode Exit fullscreen mode

Run: node sysinfo.js

Part 3: Build a JSON API Server

// api.js
const http = require("http");

const users = [
  { id: 1, name: "Pratham", role: "developer" },
  { id: 2, name: "Arjun", role: "designer" },
  { id: 3, name: "Priya", role: "manager" },
];

const server = http.createServer((req, res) => {
  if (req.url === "/api/users") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(users, null, 2));
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "Route not found" }));
  }
});

server.listen(3000, () => {
  console.log("API running at http://localhost:3000/api/users");
});
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000/api/users in your browser — you'll see JSON data. That's an API.


Key Takeaways

  1. Install Node.js from nodejs.org (pick LTS). Verify with node -v and npm -v.
  2. The REPL (node with no arguments) is an interactive playground for testing JavaScript snippets in the terminal.
  3. Run scripts with node filename.js. Your JavaScript file is read, compiled, and executed by the V8 engine — no browser required.
  4. http.createServer() creates a server that listens for HTTP requests and sends responses — your first real backend code.
  5. Use npm init -y to create a package.json for tracking project metadata, scripts, and dependencies.

Wrapping Up

You've just gone from zero to running server in one article. Node.js installed, REPL explored, scripts executed, and a multi-route HTTP server built — all without a single framework. This is the raw foundation that everything else (Express, APIs, databases) is built on top of.

I'm learning all of this through the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg. This setup was the gateway to everything else — once you can run JavaScript outside the browser and create a server, the entire backend world opens up.

Connect with me on LinkedIn or visit PrathamDEV.in. More articles on the way as the Node.js journey continues.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode

Top comments (0)