Creating and Starting a Web Server in Node.js

Node.js has the built-in http module that implements the HTTP protocol. This module can be used to create a HTTP server in Node. Similarly the https module can be used to created a HTTPS server.

Starting a HTTP Server

The createServer method can be used to create a HTTP server. Once the server is created, it can start to listen for incoming connections with the listen method.

const http = require('http');

// creates the server
const server = http.createServer((request, response) => {
    // handle incoming HTTP requests
});

// handle error while creating or starting server
server.on('error', (error) {
    console.log(error);
});

// handle error when some client connection failed
server.on('clientError', (error, socket) {
    // proper HTTP format message
    socket.end('HTTP/1.1 400 Bad Request');
});

// start listening for HTTP requests on port 8080
server.listen(8080);

For error handling there are 2 types of errors that need to be handled :

  • An error may occur while creating or starting the server. In this case the error event is emitted.
  • An error may also occur while some client is trying to connect to the server. In the case, clientError event is emitted. In this error there is no request or response object. You will need to set the response message directly to the socket.

Starting a HTTPS Server

HTTPS server can be started in the same way, but you will also need to load the SSL certificate and key as options passed to the createServer method.

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

// read the crt and key file from the server path
const options = {
    key:  fs.readFileSync('/ssl/server.key'),
    cert: fs.readFileSync('/ssl/server.crt')
};

// creates the server
const server = http.createServer(options, (request, response) => {
    // handle incoming HTTPS requests
});

// handle error while creating or starting server
server.on('error', (error) {
    console.log(error);
});

// handle error when some client connection failed
server.on('clientError', (error, socket) {
    socket.end('HTTP/1.1 400 Bad Request');
});

// start listening for HTTPS requests on port 8080
server.listen(8080);

In case of error, the error or clientError events will be emitted (as described above).