Creating a Simple Web Server in Node.js

Vitaliy Korzhenko
2 min readJul 3, 2023

--

In this article, we will explore the process of building an HTTP server from scratch in Node.js. We will dive into the fundamentals of working with HTTP and learn how to create a basic server without relying on any external frameworks. By understanding the inner workings of an HTTP server, you will gain a deeper insight into the underlying mechanisms of web communication in Node.js.

Setting Up the Project: Before we begin, ensure that you have Node.js installed on your machine. Create a new directory for your project and navigate into it using the command line. Initialize a new Node.js project by running the following command:

npm init -y

This will create a package.json file that tracks our project's dependencies.

Creating the HTTP Server: To start, let’s create a file named server.ts and open it in your favorite code editor. (like VS Code)

import http from 'http';

const hostname = '127.0.0.1';
const port = 3000;

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

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Explanation:

  • We import the http module, which is built-in to Node.js, to have access to the necessary functions for creating an HTTP server.
  • We define the hostname and port variables to specify the server's address and port number.
  • Using the http.createServer() function, we create an HTTP server. Inside the callback function, we handle incoming requests and send a response with a status code of 200 and a plain text message of "Hello, World!".
  • Finally, we call the server.listen() method to start the server, specifying the port and hostname. The server will now listen for incoming requests.

Testing the Server: Save the file and open a terminal window in the project directory. Compile the TypeScript code to JavaScript using the following command:

tsc server.ts

This will generate a server.js file that we can execute. Start the server by running the following command:

node server.js

If everything goes well, you should see the message “Server running at http://127.0.0.1:3000/" logged in the terminal.

Open your browser and navigate to http://127.0.0.1:3000/. You should see the response message "Hello, World!" displayed in the browser.

In this article, we learned how to create a simple HTTP server in Node.js using TypeScript. We explored the process of handling incoming requests and sending responses. Understanding the fundamentals of creating an HTTP server from scratch will give you a solid foundation for building more complex server applications.

Feel free to experiment with the code and explore additional features and functionalities of the http module.

--

--

Vitaliy Korzhenko

Software Developer with a keen eye for detail and a drive for delivering high-quality code