Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Node.js Tutorial

Node HOME Node Intro Node Get Started Node JS Requirements Node.js vs Browser Node Cmd Line Node V8 Engine Node Architecture Node Event Loop

Asynchronous

Node Async Node Promises Node Async/Await Node Errors Handling

Module Basics

Node Modules Node ES Modules Node NPM Node package.json Node NPM Scripts Node Manage Dep Node Publish Packages

Core Modules

HTTP Module HTTPS Module File System (fs) Path Module OS Module URL Module Events Module Stream Module Buffer Module Crypto Module Timers Module DNS Module Assert Module Util Module Readline Module

JS & TS Features

Node ES6+ Node Process Node TypeScript Node Adv. TypeScript Node Lint & Formatting

Building Applications

Node Frameworks Express.js Middleware Concept REST API Design API Authentication Node.js with Frontend

Database Integration

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert Into MySQL Select From MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit MongoDB Join

Advanced Communication

GraphQL Socket.IO WebSockets

Testing & Debugging

Node Adv. Debugging Node Testing Apps Node Test Frameworks Node Test Runner

Node.js Deployment

Node Env Variables Node Dev vs Prod Node CI/CD Node Security Node Deployment

Perfomance & Scaling

Node Logging Node Monitoring Node Performance Child Process Module Cluster Module Worker Threads

Node.js Advanced

Microservices Node WebAssembly HTTP2 Module Perf_hooks Module VM Module TLS/SSL Module Net Module Zlib Module Real-World Examples

Hardware & IoT

RasPi Get Started RasPi GPIO Introduction RasPi Blinking LED RasPi LED & Pushbutton RasPi Flowing LEDs RasPi WebSocket RasPi RGB LED WebSocket RasPi Components

Node.js Reference

Built-in Modules EventEmitter (events) Worker (cluster) Cipher (crypto) Decipher (crypto) DiffieHellman (crypto) ECDH (crypto) Hash (crypto) Hmac (crypto) Sign (crypto) Verify (crypto) Socket (dgram, net, tls) ReadStream (fs, stream) WriteStream (fs, stream) Server (http, https, net, tls) Agent (http, https) Request (http) Response (http) Message (http) Interface (readline)

Resources & Tools

Node.js Compiler Node.js Server Node.js Quiz Node.js Exercises Node.js Syllabus Node.js Study Plan Node.js Certificate

Node.js Server Reference


Server Object

Server objects in Node.js are used to create network servers. Different modules provide their own Server implementations:

  • http.Server - For creating HTTP servers
  • https.Server - For creating HTTPS servers
  • net.Server - For creating TCP servers
  • tls.Server - For creating TLS/SSL servers

These server objects handle client connections, process requests, and deliver responses as appropriate for their respective protocols.


Common Server Methods

Method Description
server.listen([port][, host][, backlog][, callback]) Starts the server listening for connections. The callback is executed when the server has been bound.
server.close([callback]) Stops the server from accepting new connections. The callback is called when all connections are closed.
server.address() Returns the bound address, the address family name, and port of the server.
server.getConnections(callback) Asynchronously gets the number of concurrent connections on the server.

Common Server Events

Event Description
'close' Emitted when the server closes.
'connection' Emitted when a new connection is made.
'error' Emitted when an error occurs.
'listening' Emitted when the server has been bound after calling server.listen().

HTTP Server

The HTTP server in Node.js is created using the http.createServer() method:

const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Handle requests
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

// Start the server
const PORT = 8080;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

// Handle server events
server.on('error', (err) => {
  console.error(`Server error: ${err.message}`);
});

server.on('close', () => {
  console.log('Server closed');
});
Run example »

HTTPS Server

The HTTPS server requires SSL certificates and is created using the https.createServer() method:

const https = require('https');
const fs = require('fs');

// SSL options - in a production environment, use properly signed certificates
const options = {
  key: fs.readFileSync('server-key.pem'),  // Path to your key file
  cert: fs.readFileSync('server-cert.pem') // Path to your certificate file
};

// Create an HTTPS server
const server = https.createServer(options, (req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Secure World\n');
});

// Start the server
const PORT = 3443;
server.listen(PORT, () => {
  console.log(`Server running at https://localhost:${PORT}/`);
});
Run example »

TCP Server (net.Server)

A TCP server is created using the net.createServer() method:

const net = require('net');

// Create a TCP server
const server = net.createServer((socket) => {
  console.log('Client connected');
  
  // Handle data from client
  socket.on('data', (data) => {
    console.log(`Received: ${data}`);
    socket.write(`Echo: ${data}`);
  });
  
  // Handle client disconnection
  socket.on('end', () => {
    console.log('Client disconnected');
  });
  
  // Handle socket errors
  socket.on('error', (err) => {
    console.error(`Socket error: ${err.message}`);
  });
});

// Start the server
const PORT = 8888;
server.listen(PORT, () => {
  console.log(`TCP server listening on port ${PORT}`);
});

// Get server information after it's listening
server.on('listening', () => {
  const address = server.address();
  console.log(`Server info: ${JSON.stringify(address)}`);
});
Run example »

TLS/SSL Server

A secure TLS/SSL server is created using the tls.createServer() method:

const tls = require('tls');
const fs = require('fs');

// SSL options
const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  
  // Request client certificate (optional)
  requestCert: true,
  
  // Reject connections without certificates (optional)
  rejectUnauthorized: false
};

// Create a TLS server
const server = tls.createServer(options, (socket) => {
  console.log('Client connected securely');
  
  // Check if client provided a certificate
  if (socket.authorized) {
    console.log('Client authorized');
  } else {
    console.log('Client unauthorized');
  }
  
  // Handle data from client
  socket.on('data', (data) => {
    console.log(`Received: ${data}`);
    socket.write(`Secure echo: ${data}`);
  });
  
  // Handle client disconnection
  socket.on('end', () => {
    console.log('Client disconnected');
  });
});

// Start the server
const PORT = 8443;
server.listen(PORT, () => {
  console.log(`TLS server listening on port ${PORT}`);
});
Run example »

HTTP Server with Routing

A more complete HTTP server with basic routing:

const http = require('http');
const url = require('url');

// Create an HTTP server with routing
const server = http.createServer((req, res) => {
  // Parse the URL
  const parsedUrl = url.parse(req.url, true);
  const path = parsedUrl.pathname;
  const trimmedPath = path.replace(/^\/+|\/+$/g, '');
  
  // Get the HTTP method
  const method = req.method.toLowerCase();
  
  // Get query parameters
  const queryParams = parsedUrl.query;
  
  // Log the request
  console.log(`Request received: ${method} ${trimmedPath}`);
  
  // Route handler
  let response = {
    status: 404,
    contentType: 'application/json',
    payload: { message: 'Not Found' }
  };
  
  // Basic routing
  if (method === 'get') {
    if (trimmedPath === '') {
      // Home route
      response = {
        status: 200,
        contentType: 'text/html',
        payload: '<h1>Home Page</h1><p>Welcome to the server</p>'
      };
    } else if (trimmedPath === 'api/users') {
      // API route - list users
      response = {
        status: 200,
        contentType: 'application/json',
        payload: {
          users: [
            { id: 1, name: 'John' },
            { id: 2, name: 'Jane' }
          ]
        }
      };
    } else if (trimmedPath.startsWith('api/users/')) {
      // API route - get user by ID
      const userId = trimmedPath.split('/')[2];
      response = {
        status: 200,
        contentType: 'application/json',
        payload: { id: userId, name: `User ${userId}` }
      };
    }
  }
  
  // Return the response
  res.setHeader('Content-Type', response.contentType);
  res.writeHead(response.status);
  
  // Convert payload to string if it's an object
  const payloadString = typeof response.payload === 'object'
    ? JSON.stringify(response.payload)
    : response.payload;
  
  res.end(payloadString);
});

// Start the server
const PORT = 8080;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
Run example »

Server Timeouts and Limits

Configuring server timeouts and connection limits:

const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Simulating a delayed response
  setTimeout(() => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Response after delay\n');
  }, 2000);
});

// Configure server timeouts
server.timeout = 10000; // 10 seconds (default is 120000 or 2 minutes)
server.keepAliveTimeout = 5000; // 5 seconds (default is 5000)
server.maxHeadersCount = 1000; // Maximum headers count (default is 2000)
server.maxRequestsPerSocket = 100; // Max requests per socket (Node.js 14+)

// Start the server
const PORT = 8080;
server.listen(PORT, () => {
  console.log(`Server with timeouts configured at http://localhost:${PORT}/`);
  
  // Display the server configuration
  console.log(`Server timeout: ${server.timeout}ms`);
  console.log(`Keep-alive timeout: ${server.keepAliveTimeout}ms`);
  console.log(`Max headers count: ${server.maxHeadersCount}`);
  console.log(`Max requests per socket: ${server.maxRequestsPerSocket || 'N/A'}`);
});
Run example »

HTTP/2 Server

Creating an HTTP/2 server (introduced in Node.js v8.4.0):

const http2 = require('http2');
const fs = require('fs');

// SSL options for HTTP/2
const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
};

// Create an HTTP/2 server
const server = http2.createSecureServer(options);

// Handle incoming streams
server.on('stream', (stream, headers) => {
  const path = headers[':path'];
  const method = headers[':method'];
  
  console.log(`${method} ${path}`);
  
  // Respond to the request
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  
  stream.end('<h1>HTTP/2 Server</h1><p>This page was served via HTTP/2</p>');
});

// Start the server
const PORT = 8443;
server.listen(PORT, () => {
  console.log(`HTTP/2 server running at https://localhost:${PORT}/`);
});
Run example »

Best Practices

  1. Error handling: Always handle server errors by listening for the 'error' event.
  2. Graceful shutdown: Implement proper shutdown procedures using server.close().
  3. Timeouts: Configure appropriate timeouts to prevent resource exhaustion.
  4. Clustering: Use the cluster module to utilize multiple CPU cores.
  5. HTTPS/TLS: Use secure servers for production applications.
  6. Connection limits: Set appropriate limits based on your server's capabilities.
  7. Monitoring: Implement monitoring for connections, requests, and response times.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.