Creating a Simple Server

Creating a simple server in JavaScript typically involves using Node.js and its built-in http module. This allows you to listen for incoming requests and send responses, forming the basis for web applications and APIs.

Illustration of Creating a Simple Server
Illustration of Creating a Simple Server

💡 Core Concept

A server listens on a specific port and handles client requests by sending back responses. Node.js simplifies this with the http module.

Here are the essential steps to create a very basic HTTP server:

  • Import the http module.
  • Create a server using http.createServer(), providing a callback to handle requests.
  • Make the server listen on a specified port (e.g., 3000).

📌 Deep Dive: Basic HTTP Server

JAVASCRIPT
const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, world!');
});

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

Explanation of the key parts:

  • http.createServer() creates the server and accepts a callback with req (request) and res (response) objects.
  • res.statusCode = 200; sets the HTTP status code to OK.
  • res.setHeader() defines the type of content being sent.
  • res.end() sends the response body and signals that the response is complete.
  • server.listen(3000) starts the server on port 3000.

⚠️ Important

Make sure Node.js is installed on your machine to run this code. Save your code in a file (e.g., server.js) and run it with node server.js.

Common HTTP Server Methods
MethodPurpose
http.createServer()Creates a new HTTP server instance
server.listen(port, callback)Starts the server on the specified port
res.statusCodeSets the HTTP response status code
res.setHeader(name, value)Sets HTTP response headers
res.end([data])Sends the response to the client and ends it

💡 Tips for Next Steps

Once comfortable with this, try sending HTML content, handling different URLs, or using frameworks like Express.js for more features.