DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Edited on • Originally published at webcraft-notes.com

Getting Started with Node.js: Building a Basic Web Server

Building a Basic Web Server

Check this post in my web notes.

As I started exploring Node.js, I realized the value of documenting my learning process. These online notes aim to simplify the often intricate concepts, providing a beginner-friendly resource for those venturing into the world of Node.js. Additionally, this process of compiling these notes has immensely helped me structure and solidify my newly acquired knowledge. I hope these insights serve as a helpful guide, smoothing out the initial hurdles and fostering a clearer understanding as you begin your journey in this exciting realm of web development.

What is Node.js? Node.js is a platform that allows you to run JavaScript code outside of a web browser. It's useful because it lets developers use JavaScript to build server-side applications, enabling them to create dynamic web content, handle databases, and perform various tasks on the server. In simple terms, Node.js expands the capabilities of JavaScript beyond just websites, allowing it to power entire web applications and services. But it's only words, let's make some interesting and practical staff.

In this post, we will start with creating a simple Web Server and will try to understand the modules in Node.js. To work with Node.js we need to install Node.js runtime environment from the official website, and after we can start:

Modules in Node.js

In Node.js, modules are like building blocks or tools that help organize and structure code. They are individual files that contain functions, variables, or pieces of code that can be reused in different parts of a program. Modules make it easier to manage and maintain code by breaking it into smaller, manageable chunks, allowing developers to create more organized and scalable applications. So if we want to use some functionality we might import Node.js module that already has that functionality or create one. To import a module we need to use the "require" function and pass the module as a parameter.

HTTP Module

In our case, we need to include a built-in HTTP module that allows us to create HTTP servers and make HTTP requests. It provides functions and classes to handle HTTP-related operations.
To create an HTTP server using the HTTP module, you can use the "http.createServer()" method. Here's a basic example:

const http = require('http');
const server = http.createServer();
Enter fullscreen mode Exit fullscreen mode

But that's not all, inside our "http.createServer()" method we need to add a callback function that will take care of server (req, res) requests and responses.

  • req. It contains information about the request made by the client, such as the URL, headers, parameters, etc.

  • res. It's the object that the server uses to send data back to the client in response to the request.

Build Simple Server

In our simple server, we will use the response method "writeHead()" with params: status code, and object that will contain header params. Then we will use "end()" method it tells the server that all response headers and content have been sent back to the client, effectively ending the response. Let's check the example:

const http = require('http');
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, this is a simple web server!');
});
Enter fullscreen mode Exit fullscreen mode

And the last touch, we need to add "server.listen()" - it is a method in Node.js used to start the server and make it listen for incoming connections on a specified port.

const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, this is a simple web server!');
});

server.listen(port, () => {
  console.log(`Server running at localhost:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Once "server.listen()" is called, the server starts running and is ready to handle incoming HTTP requests on the specified port.
That's it, now we can use the command "node " to start our server and check the result in the browser in "localhost: 3000" route. And the result:
simple server resultCongratulations, we've successfully created our first simple web server in Node.js! However, this achievement marks just the beginning of our journey through the expansive realm of Node.js. There's so much more to explore and learn on this exciting path of Node.js development. Let's continue this journey together, diving deeper into the vast possibilities and intricacies that Node.js offers.

Thank you for reading. Also, visit my blog for more articles. )

Top comments (0)