Setting up Node.js server (HTTP server): installing on Windows; components - required modules, Create Server (http.createServer()), Request and response

Five lines make a web server: require the http module, createServer with a function receiving req and res, answer through res, and listen on a port: localhost:8080 is live.

11 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Five lines to a live server

Web servers used to feel like infrastructure: something installed by serious people in server rooms.

Today you will write one in 5 lines, run it with node app.js, and visit it in your own browser at an address that never leaves your machine. FestConnect's back end, the box Unit 4 only drew, boots for the first time.

The recipe needs 3 components: the http module, one callback function, and a port.

Theory

The components, named

  • The http module: Node ships a built-in library for speaking HTTP; require('http') loads it (modules get their full lesson next)
  • createServer(callback): builds the server; the callback is your counter clerk: it runs once for every incoming request
  • req and res: the callback's 2 arguments: req describes what the visitor asked (their URL, method, headers); res is the reply you assemble and send
  • listen(port): opens the shop on a numbered door: server.listen(8080)

Practical

app.js: FestConnect's first server

const http = require('http');          // 1: load the http module

const server = http.createServer(function (req, res) {
    // this function runs ONCE PER REQUEST
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('<h1>FestConnect Live</h1>');
    res.write('<p>Seats left for Garba Night: 40</p>');
    res.end();                          // finish and send the reply
});

server.listen(8080);                    // open door number 8080
console.log('Server running at http://localhost:8080');

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Follow along

From file to first visit

  1. Save the listing as app.js Any folder; plain text; the name is convention, not law.
  2. Run: node app.js The command prompt prints the console.log line and then... nothing. That stillness means the server is ALIVE, waiting. Ctrl+C stops it.
  3. Visit http://localhost:8080 in a browser localhost = this very machine; 8080 = the door you opened. The heading appears: your first self-served page.
  4. Refresh a few times Each refresh is a fresh request; your callback runs again every time.

Theory

req and res: the two ends of one conversation

Every request wakes your callback with 2 objects:

req (the request): everything the visitor sent: most useful now is req.url, the path they asked for ("/", "/schedule", "/?event=garba": lesson 24 reads it).

res (the response): your reply, assembled in 3 moves: writeHead (status + headers, first), write (body content, repeatable), end (seal and send: without it the browser waits forever).

Notice who else you met in Unit 4: your AJAX code was the OTHER side of these exact objects: what xhr sent became req; what res sends becomes responseText.

Quiz

In http.createServer(function (req, res) {...}), when does that function actually execute?

  1. Once, when node app.js starts the server
  2. Once for EVERY incoming request: each visit and refresh runs it again
  3. Continuously, in a loop, while the server is running
  4. Only when res.end() is called somewhere
Show the answer

Once for EVERY incoming request: each visit and refresh runs it again

The callback is the counter clerk: it sleeps until a request arrives, serves it, and sleeps again: 10 visitors mean 10 executions, and every browser refresh in the steps above re-ran it. Option A describes listen()'s one-time role of opening the door, a different moment. Option C would burn the single thread the event loop protects: Node runs your code ONLY in response to events. Option D reverses cause and effect: res.end() is how each execution FINISHES its reply, not what triggers one.

Think first

The spinner that never stops

A classmate's server has writeHead and write but he forgot res.end(). He visits localhost:8080. Before tapping: what exactly does his browser do, and why does this bug follow from how HTTP responses work?

Show the answer

The tab spins forever: content may even appear (write sent it in chunks), but the browser keeps waiting because nothing ever said THE REPLY IS COMPLETE. res.end() is that signal: HTTP responses are open streams until explicitly finished, a design that lets big pages flow in pieces (Node's no-buffering feature from last lesson). No error, no crash: just an eternally loading tab, which makes forgotten end() calls one of Node's most recognisable beginner bugs. Every response path must reach an end().

Watch out

Setup snags

Port already in use: EADDRINUSE on listen means another program (often your own forgotten server in another window) owns 8080: stop it or pick 8081.

Edits do nothing: Node loaded your file at start; changes need a restart (Ctrl+C, node app.js again).

localhost is yours alone: classmates cannot visit your localhost:8080; it never leaves your machine: deployment is a later course's story.

Theory

The circle from Unit 4 closes

Replace the listing's HTML with a JSON string and Content-Type application/json, and THIS server can answer the exact xhr.open("GET", ...) calls your AJAX pages make: you now hold both ends of the wire, in one language. Two refinements remain: organising code into modules (next), and reading what the visitor actually asked for from the query string (after that): then FestConnect's server does real work.

Summary

Key takeaways

  • Components: the http module (require('http')), createServer with a callback, req + res, and listen(port).
  • The callback runs once per incoming request: the event loop serving visitors.
  • req = what they asked (req.url); res = your reply: writeHead, then write, then end.
  • res.end() seals and sends; forgetting it leaves the browser spinning forever.
  • server.listen(8080) opens the door; visit http://localhost:8080 (this machine, that port).
  • Code edits need a server restart; port clashes mean another server holds that door.
  • Memory hook: require, create, listen: head, body, end.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Node.js

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Setting up Node.js server (HTTP server): installing on Windows; components - required modules, Create Server (http.createServer()), Request and response · Web Designing-2 (option A) · Gri-Learn