Node.js: Code Outside the Browser / Building a Basic Server-Side Application (Without Framework)

Creating a Simple Web Server

🎯 Goal of This Note

Learn how to create a basic web server using Node.js that can accept requests from a browser and send back responses.


πŸ‘·β€β™‚οΈ Setup

  1. πŸ“₯ Grab the starter files for this section and open the project folder.

    Download the Repo & Open starter folder inside : 1-node-farm
    https://github.com/codevedadev/complete-node-bootcamp

  2. πŸ“„ Create a new file: index.js

  3. πŸ“ If you already have it ready, skip this step.


πŸ“¦ Step 1: Import the http Module in index.js File

const http = require('http');
  • The http module is another built-in Node.js module (just like fs).

  • It gives Node networking capabilities β€” specifically, the ability to build a web server.

Tip: It's helpful to comment out any earlier file-reading/writing code at this point, and organize your file with comments like // FILES and // SERVER to separate sections clearly.


πŸ› οΈ Step 2: Building a Server β€” Two Main Steps

To create a working server in Node.js, you need to:

  1. Create the server.

  2. Start (listen on) the server so it can accept incoming requests.

🌐 Creating the Server

const server = http.createServer((req, res) => {
  res.end('Hello from the server!');
});

πŸ”Ž Code Breakdown

πŸ‘·β€β™‚οΈ Building the Server

  • http.createServer() creates a new server.

  • It accepts a callback function that runs every time a new request hits the server.

  • This callback receives two important objects:

    1. req (request) β€” contains information about the incoming request (e.g., the URL requested, headers, etc.)

    2. res (response) β€” provides tools for sending a response back to the client (browser)

πŸš€ Sending a Response

res.end('Hello from the server!');
  • res.end() is the simplest way to send a plain text response back to whoever made the request.

  • (The reason it's called .end will make more sense later β€” for now, just know it sends and finishes the response.)

Note: Deeper concepts like "requests," "responses," and the client-server model will be explained in a dedicated upcoming lecture on how the web works. For now, the focus is on getting things working practically first, theory later.


πŸš€ Step 3: Starting the Server (Listening for Requests)

server.listen(8000, '127.0.0.1', () => {
  console.log('Listening to requests on port 8000');
});

βš™οΈ Breakdown of .listen()

This method is called on the server variable (the result of createServer) and takes:

  1. πŸšͺ Port number β€” e.g., 8000

    • A port is like a sub-address on a specific host/computer.

    • Common port numbers used in Node development: 8000, 3000, 80, etc.

  2. 🌐 Host (optional)

    • '127.0.0.1' is the standard IP address for localhost (meaning "this current computer").

    • If not specified, it defaults to localhost automatically.

  3. πŸ“’ Callback function (optional)

    • Runs once the server successfully starts listening.

    • Commonly used to log a confirmation message like:

      Listening to requests on port 8000

▢️ Step 4: Running the Server

In the terminal:

node index.js
  • You'll see the log message: Listening to requests on port 8000

  • Unlike previous scripts, this program does NOT exit automatically β€” it keeps running.

    • This is because the server must stay active to keep listening for new requests.

    • This behavior relates to something called the event loop, which will be explained in more detail later in the course.


🌐 Step 5: Testing the Server in a Browser

  1. Open a browser.

  2. Go to: (host, followed by a colon :, followed by the port number)

    localhost:8000 **OR** 127.0.0.1:8000
  3. You should see the message: Hello from the server!

πŸŽ‰ Congratulations β€” you now have a real, working web server running on your computer using Node.js!


πŸ›‘ Step 6: How to Stop the Server

  • Unlike the REPL (Ctrl + D), a running Node script is stopped with:

Ctrl + C

(Even on Mac β€” use Control, not Command.)

  • This is the standard way to stop any Node script from here on out.


πŸ” Step 7: Exploring the Request Object

You can inspect the req (request) object to see what data it contains:

const server = http.createServer((req, res) => {
  console.log(req);
  res.end('Hello from the server!');
});
  • After making changes to code, remember to:

    1. Stop the server (Ctrl + C)

    2. Restart it (node index.js)

    3. Refresh the browser page to trigger a new request

  • The req object contains a large amount of data, including:

    • HTTP headers (like host)

    • Many other properties (too much to display fully in the console)

HTTP headers will be explained in more detail in an upcoming topic.


πŸ”„ Recap: What Just Happened

  1. πŸ—οΈ We created a server using http.createServer(), passing in a callback that runs on every incoming request.

  2. πŸš€ We started the server using server.listen(), specifying the port and host (localhost).

  3. 🌐 When we visited localhost:8000 in the browser, it triggered a request.

  4. ⚑ Internally, Node fired an event, which triggered our callback function.

  5. πŸ“€ The callback sent back the response: "Hello from the server!"