Thuta Learning
Node.js
BasicWeb DevelopmentBeginner

Your First App

Node.jsLesson 425 min

What you'll walk away with

  • Create a server with createServer() and send back a status code, a header and a body
  • Explain what listen(port, host, callback) does and why a server keeps the process alive
  • Test a server from the same script using port 0 and fetch()
  • Diagnose first-server problems such as EADDRINUSE and a forgotten res.end()

Explain it simply

Explain it simply

The scripts in earlier lessons ended once their last line ran. A server is more like a shop: it opens its door and waits for customers (requests). Each time a customer walks in, it listens to the question and gives an answer (a response).

A shop stays open until you close it, and a server keeps running until you press Ctrl + C or call close() from your code. A terminal that seems stuck is simply a shop with its door open.

Problem → Why → Solution

The problem: the server seems to freeze

Beginners usually hit three problems with their first server: the terminal never returns to the prompt, so they think the program froze; the browser spins forever; and a second run fails with EADDRINUSE. The code below has the second problem: it starts writing a response but never finishes it.

broken-server.mjs
import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.write("Hello");
  // forgot res.end(): the browser keeps waiting for more
});
server.listen(3000);

// Second copy started in another terminal:
// Error: listen EADDRINUSE: address already in use :::3000

Why does this happen?

A listening server tells the event loop that work is still pending, so the process does not end; that is intended, not a freeze. An HTTP response only finishes when you call res.end(). And only one process at a time can listen on a given port.

Core concept: one request, one handler call, one response

createServer(handler) creates a server object. Every time a request arrives, Node calls the handler with two arguments, req and res. req (an IncomingMessage) carries what the client sent: the method (GET, POST), the url (a path such as "/hello?x=1") and the headers. res (a ServerResponse) is how you answer: set statusCode, add headers with setHeader(), write body chunks with write() and finish with end(). Calling end() with text writes it and closes the response in one step.

server.listen(port, host, callback) asks the operating system for the port and calls the callback once it has it. A host of "127.0.0.1" accepts connections from your own machine only, while "0.0.0.0" accepts them from other machines on the network too. Port 0 lets the OS pick any free port, which you read back from server.address().port; that is very handy in tests.

While the server listens, the event loop holds an open handle, so the process stays alive. server.close() stops accepting new connections and releases the handle once existing ones finish, and then the process ends naturally. Ctrl + C in the terminal sends a SIGINT signal, and Node's default reaction is to stop the process at once.

Common memberWhat it gives you or does
req.methodThe HTTP method, such as "GET" or "POST": what the client wants to do
req.urlThe path plus query string ("/users?page=2"), without the host
req.headersAn object of headers with lowercase names as keys
res.statusCodeThe response status, 200 unless you change it
res.setHeader(name, value)Adds one header before the body is sent
res.end(body)Writes the last of the body and closes the response

After every code change you must restart the server, because Node reads the file only once at startup. node --watch app.mjs restarts it for you whenever the file changes.

Mental model: the life of one request
  1. listen() opens the port
  2. A client sends a request
  3. Node calls handler(req, res)
  4. res.end() completes the response
  5. Server waits until close()

The handler runs once per request, and every response must be closed with end().

General pattern: an HTTP server

javascript
import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.statusCode = statusNumber;
  res.setHeader("Header-Name", "value");
  res.end(bodyText);
});

server.listen(port, host, () => {
  // the port is open; requests can arrive now
});

Inside the handler you build the response in order: status, headers, body. Headers must be set before the body goes out. listen()'s callback runs only after the port is open, so that is where a "server ready" log belongs.

Example: a server that sends itself one request

This app starts a Hello World server on port 0 and uses Node's built-in fetch() to request /hello. It prints the response's status, header and body, then closes the server so the program ends on its own. You see the whole round trip without opening a browser.

app.mjs
// app.mjs - a first web server that sends itself one request
import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
  res.end(`Hello World from Node.js! You asked for ${req.url}\n`);
});

// Port 0 = "any free port", so this example never clashes with another app.
server.listen(0, "127.0.0.1", async () => {
  const { port } = server.address();
  console.log("Server is listening on 127.0.0.1");

  const response = await fetch(`http://127.0.0.1:${port}/hello`);
  console.log("Status:", response.status);
  console.log("Content-Type:", response.headers.get("content-type"));
  console.log("Body:", (await response.text()).trim());

  server.close(() => console.log("Server closed, so the process can exit"));
});

Code breakdown

  1. Line 4const server = createServer((req, res) => {

    You write the handler once and Node calls it for every request. This example sends a single request, so it runs once.

  2. Line 6res.setHeader("Content-Type", "text/plain; charset=utf-8");

    Content-Type tells the client what kind of body this is. charset=utf-8 makes non-English text, such as Myanmar script, display correctly.

  3. Line 7res.end(`Hello World from Node.js! You asked for ${req.url}\n`);

    end() writes the body and closes the response. req.url holds only the path, without the host, so it echoes "/hello".

  4. Line 11server.listen(0, "127.0.0.1", async () => {

    Port 0 asks the OS for any free port. The callback runs only once the port is open, so sending the request from inside it is safe.

  5. Line 15const response = await fetch(`http://127.0.0.1:${port}/hello`);

    Since Node 18, fetch() is a global, so no import is needed. This request is exactly what a browser would send.

  6. Line 20server.close(() => console.log("Server closed, so the process can exit"));

    Without close(), the server would keep listening and the program would never end. Once closed, the callback runs and, with no open handles left, the process exits.

You should see
Server is listening on 127.0.0.1
Status: 200
Content-Type: text/plain; charset=utf-8
Body: Hello World from Node.js! You asked for /hello
Server closed, so the process can exit

The everyday version that keeps running

A real project never closes its server: it listens on a fixed port, and you open http://127.0.0.1:3000/ in a browser. Run the version below with node server.mjs or node --watch server.mjs and stop it with Ctrl + C. Checking req.url and answering each path differently is the start of routing, which Express will make easier later.

Try it: open /, then /about, and watch the status change from 200 to 404 in the browser's Network tab. Then start a second copy in another terminal and read the EADDRINUSE error for yourself, so you recognise it instantly next time.

server.mjs
import { createServer } from "node:http";

const port = Number(process.env.PORT ?? 3000);

const server = createServer((req, res) => {
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
  if (req.url === "/") {
    res.end("Home page\n");
  } else {
    res.statusCode = 404;
    res.end(`No page at ${req.url}\n`);
  }
});

server.listen(port, "127.0.0.1", () => {
  console.log(`Server running at http://127.0.0.1:${port}/ (Ctrl + C to stop)`);
});

In real projects

Where this pattern lives in real projects

Express, Fastify and Koa all use a node:http server underneath. Routes, middleware and JSON parsing are layers wrapped around the same handler(req, res) you wrote here, so understanding req and res makes framework errors much easier to debug.

Hosting platforms usually tell your app which port to use through the PORT environment variable, so reading process.env.PORT is standard. Inside a Docker container you listen on 0.0.0.0 so connections from outside the container can reach you. Load balancers call an endpoint such as /health repeatedly and stop sending traffic if it does not return 200. Automated tests do exactly what this example does: start the server on port 0, send requests, then close() it, so parallel test runs never fight over a port.

Common mistakes

Common mistakes

1. Forgetting res.end() on one code path

If one branch of an if/else handler never calls end(), clients hitting that URL wait for the response to finish until Node's request timeout cuts the connection. Check that every branch ends with res.end(), or write return res.end(...) in each one.

2. Starting the server twice (EADDRINUSE)

Running the server in a second terminal tab while the first is still running gives "listen EADDRINUSE: address already in use". Stop the first copy with Ctrl + C, or pick another port such as PORT=3001.

3. Setting a header after the body went out

Calling setHeader() after res.end() or the first res.write() throws ERR_HTTP_HEADERS_SENT, because the headers have already been sent. Always set the status and headers first.

Best practices

Best practices

  • Read the port from process.env.PORT instead of hard-coding it, with a default such as 3000 only for local development.
  • Keep the "server running" log inside listen()'s callback so it only appears once the port is really open.
  • Send a Content-Type with charset=utf-8 on every text response.
  • Keep the handler thin and move logic into separate functions, which you can then test without HTTP at all.

Mini challenge

Mini challenge: a command-line greeting app

Not every app is a server. Write greet.mjs, which takes a name and a --shout option from the terminal and prints a greeting, using parseArgs() from node:util. Test several command lines by passing argument arrays instead of retyping them in the terminal.

  • greetingFor(argv) takes an argument array and returns a string
  • Use "World" as the default when no name is given
  • Return upper case when --shout (or -s) is present
  • Print the error code for an unknown option such as --loud
greet.mjs
// greet.mjs - run it with: node greet.mjs Aye --shout
import { parseArgs } from "node:util";

function greetingFor(argv) {
  // TODO: parseArgs with args: argv, allowPositionals: true
  //       and a boolean "shout" option with short name "s"
  // TODO: build "Hello, <name>!" with "World" as the default name
  // TODO: upper-case it when shout is true
}

// TODO: try [], ["Aye"], ["Aye", "--shout"], ["Aye", "--loud"]
//       print "node greet.mjs <args> -> <result or err.code>"

Expected: The output should be: node greet.mjs -> Hello, World! node greet.mjs Aye -> Hello, Aye! node greet.mjs Aye --shout -> HELLO, AYE! node greet.mjs Aye --loud -> ERR_PARSE_ARGS_UNKNOWN_OPTION

Show hint

parseArgs() returns { values, positionals }. positionals[0] ?? "World" gives the default name. In strict mode (the default) parseArgs throws on unknown options, so wrap the call in try/catch and read err.code. For a real run, pass process.argv.slice(2): the first two items are the node path and the script path.

Show solution
greet.mjs
// greet.mjs - run it with: node greet.mjs Aye --shout
import { parseArgs } from "node:util";

function greetingFor(argv) {
  const { values, positionals } = parseArgs({
    args: argv,
    allowPositionals: true,
    options: { shout: { type: "boolean", short: "s", default: false } },
  });
  const greeting = `Hello, ${positionals[0] ?? "World"}!`;
  return values.shout ? greeting.toUpperCase() : greeting;
}

// Try a few command lines without retyping them in the terminal.
for (const argv of [[], ["Aye"], ["Aye", "--shout"], ["Aye", "--loud"]]) {
  const command = ["node greet.mjs", ...argv].join(" ");
  try {
    console.log(`${command} -> ${greetingFor(argv)}`);
  } catch (err) {
    console.log(`${command} -> ${err.code}`);
  }
}

// Real use: console.log(greetingFor(process.argv.slice(2)));

Quick quiz 1 / 3

After node app.mjs prints "Server running...", the terminal prompt never comes back. Why?

Quick quiz 2 / 3

In server.listen(0, "127.0.0.1", cb), what does port 0 mean?

Quick quiz 3 / 3

A handler calls res.write("Hi") but never res.end(). What does the browser experience?

What to remember

  • createServer(handler) calls handler(req, res) once for every request.
  • Build the response as status, then headers, then body, and always finish with res.end().
  • A listening server keeps the process alive; stop it with Ctrl + C or server.close().
  • Port 0 plus fetch() is the easy way to exercise a server from a script.

Run Node.js scripts — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Your First App | Thuta Learning