Skip to main content

Command Palette

Search for a command to run...

Building Server in Nodejs

Updated
β€’4 min read
Building Server in Nodejs
N
πŸš€ Greetings World! 🌐 Meet a dynamic Frontend Developer, UI/UX Designer, and avid explorer of Cloud & DevOps realms! Uncover the journey of a professional deeply passionate about crafting seamless user experiences, designing visually stunning interfaces, and navigating the cloud with a DevOps mindset. πŸ”§ Skills Snapshot: - Frontend Mastery: HTML, CSS, and JavaScript expert, specializing in React, Angular, and Vue.js. - Design Wizardry: Proficient in wireframing, prototyping, and Adobe Creative Suite and Figma for captivating designs. - Cloud Maestro: Fluent in AWS, Azure, and Google Cloud Platform, adept at architecting scalable solutions. - DevOps Guru: Skilled in Docker, Kubernetes, Jenkins, and Git, contributing to efficient development workflows. πŸ”— Let's Connect: Open to collaborating on exciting projects and sharing industry insights, I invite connections for networking or discussions. Reach out for potential collaborations. πŸ“§ Contact Me: -Portfolio:[https://www.nehalingole.in/] - GitHub: [GitHub Profile](https://github.com/Ingole712521) - Email: [nehalingole2001@gmail.com](mailto:nehalingole2001@gmail.com) - Mobile: 7397966719 - Figma: [Figma Profile](https://www.figma.com/@nehalingole) - Twitter: [Twitter Profile](https://twitter.com/IngoleNehal) - HashNode: [HashNode Profile](https://hashnode.com/@Nehal71) - LinkedIn : [LinkedIn Profile](https://www.linkedin.com/in/nehal-ingole/)

Introduction

Node.js is a powerful runtime environment that allows you to build scalable and efficient server-side applications using JavaScript. In this guide, we'll walk through the process of creating a server in Node.js from scratch. By the end of this tutorial, you'll have a solid understanding of how to set up a basic server, handle HTTP requests, and build RESTful APIs.


Fs module

node-http-server - Codesandbox

In Node.js, the fs (file system) module provides an API for interacting with the file system on your machine. It allows you to perform various file-related operations such as reading, writing, updating, and deleting files and directories. In this blog, we'll explore the capabilities of the fs module and learn how to use it effectively in your Node.js applications.

Certainly! The provided code snippet utilizes the Node.js fs (file system) module and the os (operating system) module to perform file system operations and retrieve information about the system's CPUs, respectively. Let's break down the code and explain it in detail:

const fs = require('fs'); // Importing the file system module
const os = require('os'); // Importing the operating system module
  • fs: The fs module in Node.js allows you to perform file system operations such as reading, writing, and manipulating files and directories.

  • os: The os module provides a way of interacting with the operating system. In this code, we're using it to retrieve information about the system's CPUs.

console.log(os.cpus().length); // Print the number of CPU cores
  • os.cpus(): This method returns an array containing information about each CPU core on the system. We use .length to determine the number of CPU cores available.
fs.writeFileSync("./file.txt" , "Hello World"); // Blocking file write operation (Synchronous)
  • fs.writeFileSync(): This method writes data to a file synchronously, meaning it blocks the execution of the script until the operation is complete. In this case, it writes the string "Hello World" to a file named file.txt in the current directory.
fs.writeFile("./file.txt" , "Hello World" , (err) => {
  console.log();
}); // Non-blocking file write operation (Asynchronous)
  • fs.writeFile(): This method writes data to a file asynchronously, meaning it does not block the execution of the script. It takes a callback function that is executed once the operation is complete or encounters an error. In this case, it also writes the string "Hello World" to the file.txt file, but asynchronously.

Building a Basic HTTP Server

Creating your first self implemented basic HTTP server (with routing) in  Node.js | Our Code World

Introduction

Node.js allows you to create powerful servers easily using its built-in HTTP module. In this blog, we'll explore how to build a basic HTTP server in Node.js using the http module. We'll also demonstrate how to handle HTTP requests and log them to a file using the fs module.

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

const myServer = http.createServer((req, res) => {
  // Server logic goes here
});

const PORT = 8000;
myServer.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));

In this code, we create an HTTP server usin the http.createServer() method and specify a callback function to handle incoming requests.

HomePage

About Page

Contact-us

Another page (404 not found)


Handling HTTP Requests

Next, we'll define the logic to handle different HTTP requests based on the requested URL.

const myServer = http.createServer((req, res) => {
  const log = `${Date.now()}: ${req.url} - New request received\n`;
  fs.appendFile('log.txt', log, (err) => {
    if (err) console.error('Error logging request:', err);
  });

  switch (req.url) {
    case '/':
      res.end('Hello from the server');
      break;
    case '/about':
      res.end('I am Nehal Ingole');
      break;
    case '/contact-us':
      res.end('You can contact me');
      break;
    default:
      res.end('404 Not Found');
  }
});

This code appends a log entry to a file (log.txt) for each incoming request and handles different URLs with appropriate responses.

Logging Requests to a File

We use the fs.appendFile() method to log each request to a file named log.txt. This helps in tracking and debugging incoming requests.


Conclusion

In this series, we've taken a deep dive into the world of Node.js, exploring its vast capabilities and functionalities. We've covered everything from building basic servers to mastering advanced concepts like streams and asynchronous programming. Whether you're a beginner looking to get started with Node.js or an experienced developer aiming to sharpen your skills, we hope this series has provided valuable insights and knowledge to help you succeed in your Node.js journey.

Thank you for joining us on this exhilarating journey through the realm of Node.js! We've covered a lot of ground, but remember, learning is a continuous process. Keep experimenting, keep exploring, and keep pushing the boundaries of what you can achieve with Node.js. Stay tuned for more exciting content, and until next time, happy coding!

Connect with us:

Node

Part 1 of 8

πŸš€ Dive into Node.js with us! From basic servers to advanced concepts like streams and async programming, there's something for everyone in this exciting series! πŸŽ‰ #NodeJS #Programming

Up next

Handling URLs in Node.js

Node.js provides powerful modules for handling URLs, allowing developers to parse, manipulate, and interact with URL strings easily. In this blog post, we'll explore some common tasks related to handling URLs in Node.js. Parsing URLs Node.js provides...

More from this blog

R

Read & Learn

88 posts

Get ready for a journey through the captivating realms of projects and technology!

πŸ’‘ Our upcoming blogs are your ticket to a world of insights, coding wizardry, and a dash of innovation.