🎓 A1Learner
🔍
0 of 50 lessons completed

Your First Server

A server is a program that waits for visits and answers them. The http module builds a server with one function call.

Make a server

This code makes a server that answers every visit the same way.

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

Start the server

This line starts the server on port 3000.

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

Example

const http = require('http');

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

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

Key points

  • A server is a program that waits for visits and answers them.
  • A visit is a request sent to the server's address.
  • createServer makes a server from a function.
  • The function runs once for each visit to the server.
  • The name res stands for the response, the reply the server sends.
  • The function sends a reply with res.end.
  • listen starts the server on a port.
  • A port is a number that names a door into the computer.
  • Port 3000 is a common choice for a small test server.
  • localhost is the name for your own computer.
  • The address http://localhost:3000/ points at the server on your own computer.

In this example, createServer makes a server that answers every visit with Hello from Node!. The listen line starts the server on port 3000. A visit to http://localhost:3000/ answers Hello from Node!. The startup line prints Server running on port 3000.

Note

The server keeps running until you stop it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does server.listen(3000) do?