Creating a Server

createServer takes a handler that runs for every request.

Syntaxhttp.createServer((req, res) => { ... })

http.createServer takes a handler function that runs once for every incoming request. Inside it, you inspect the request and build a response.

An HTTP request flows from client to server and a response flows backClientNode ServercreateServerrequest (req)response (res)
The client sends a request; your handler builds and returns a response.

Always finish a response by calling res.end(), or the client will hang waiting.

Example

Example Β· javascript
const http = require('http');

const server = http.createServer((req, res) => {
  console.log(`${req.method} ${req.url}`);
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Welcome!\n');
});

server.listen(3000);

When to use it

  • A company's internal dashboard is served by a Node HTTP server that reads HTML templates from disk and streams them to the browser.
  • An automated test harness spins up a real `http.Server` instance before each test suite to exercise full request/response cycles in isolation.
  • A developer uses `server.close()` in process signal handlers to ensure all in-flight requests finish before the container restarts.

More examples

Create, start and stop a server

Shows how to bind to a specific host/port and cleanly close the server on a SIGINT signal.

Example Β· js
const http = require('http');

const server = http.createServer((req, res) => res.end('OK'));

server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/');
});

// Graceful shutdown on Ctrl+C
process.on('SIGINT', () => server.close(() => process.exit(0)));

Track active connections

Uses server-level events to track and expose the current number of open connections.

Example Β· js
const http = require('http');
let connections = 0;

const server = http.createServer((req, res) => {
  res.end(`Active connections: ${connections}`);
});

server.on('connection', () => connections++);
server.on('close',      () => connections = 0);
server.listen(3000);

Serve static HTML from file

Reads an HTML file synchronously (acceptable for a simple server) and serves it for every request.

Example Β· js
const http = require('http');
const fs   = require('fs');

http.createServer((req, res) => {
  const html = fs.readFileSync('index.html');
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end(html);
}).listen(3000);

Discussion

  • Be the first to comment on this lesson.
Creating a Server β€” Node.js | SoundsCode