Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Beginners

    NextJS Tutorial: Getting Started with NextJS

    Programming

    Programming Patterns. SOLID principle

    GraphQL

    Optimizing Graphql Data Queries with Data Loader

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 10: Nodejs as a Web Server
    Node.js

    Node.js Lesson 10: Nodejs as a Web Server

    Mohammad Shad MirzaBy Mohammad Shad MirzaNovember 13, 2020Updated:November 25, 2020No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 10: Nodejs as a Web Server
    Node.js Lesson 10: Nodejs as a Web Server
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Node.js Lesson 10: Nodejs as a Web Server
    Node.js Lesson 10: Nodejs as a Web Server

    Hey everyone, today we going to learn how to create a web server using the HTTP module. We will learn more about this module and use our knowledge about EventEmitter from the previous lesson. We will also see how to serve an HTML file from the webserver we created. Let’s start.

    What is a Web Server

    A Web Server is an HTTP server whose job is to accept HTTP requests and return a response. It’s a piece of backend code running on a machine somewhere that serves our request. Whenever we type a URL in the address bar and request a web page, there is a web server who takes our request and returns the appropriate webpage. The files that we need to visit the webpage are hosted or stored on a web server and it understands the URLs very well. It reads the requested URL, checks which file needs to be accessed, and returns that file as a response.

    In this way, the main task of the webserver is to store the webpages, process, and deliver them as they are requested. This response can either be an HTML file for web pages or a JSON output for an API. To be honest, we can’t imagine the internet without web servers. Sounds interesting right? Let’s create one ourselves.

    How to Create a Web Server

    Now that we understand the job of a web server, it will be much easier for you to follow along. We will use our good old http module to create a web server. Let’s follow the process one step at a time.

    Step 1: Set up a project directory

    This is a new app so let’s set it up in a fresh directory. We will name the directory web_server. Once you’re done, enter the folder and create a file server.js. We will add all our code in this file.

    Step 2: Create a server and listen to a port

    Let’s import the http module first. http module has a method createServer() which is used to instantiate server. After that, we will listen to incoming requests on a particular post.

    const http = require('http');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        // add code to handle requests
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    server.listen() starts listening to incoming requests on port number and host passed in the first and second arguments. The third argument is a callback that gets called once the server starts listening. We are logging a message so that we know that the server setup is completed successfully.

    Read More:  24. Node.js Lessons.Reading Parameters From the Command Line and Environment.

    Did you notice the arguments received by callback in the createServer() method? Let’s talk about what are those.

    The first argument req is the request object. It contains information about the request. It will answer questions like what type of request is this? Is there any data passed along with it? What are query parameters? etc.

    The second argument res is the response object. We will use it to return a response when the request is successful or return an error in case of failure. We will also set the HTTP response status on this object to better explain the type of response. 404 is “file not found” error, 500 is “server error” and 200 status code is for “the successful requests“. Of course, there are many more, you can check the whole list on this link.

    Step 3: Handle Incoming Requests

    There are few methods attached to req and res objects. We can use those to perform different operations. Let’s see how:

    const http = require('http');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const url = req.url;
        if (url === '/text'){
            res.end("Hello from Server");
        }
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    Here, we are checking for url from the request object and if its value is “text”, we will return a string response using res.end(). Let’s see the output we get on the browser for this response.

    Text response from Web Server
    Text response from Web Server

    But the plain text is not the only format we can use to send a response. HTML, JSON, and CSV formats can also be sent similarly. We just need to tell our response object about what type of data we are sending. We can do that using headers on the response.

    const http = require('http');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const url = req.url;
        if (url === '/text'){
            res.end("Hello from Server");
            return;
        }
    
        if (url === '/json'){
            res.setHeader("Content-Type", "application/json");
            res.writeHead(200);
            res.end(`{"message": "Hello from Server"}`);
            return;
        }
    
        if (url === '/html') {
            res.setHeader("Content-Type", "text/html");
            res.writeHead(200);
            res.end(`<html><body><h1>Hello from Server</h1></body></html>`);
            return;
        }
    
        if (url === '/csv'){
            res.setHeader("Content-Type", "text/csv");
            res.writeHead(200);
            res.end(`name,emailn1,John Doe,john@example.com`);
            return;
        }
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });
    

    We are using multiple if block to determine which type of response to send. Then we set headers using the setHeader() method. This info is needed to parse the response. We set the status code using the writeHead() method and return the response with end().

    Read More:  Dockerization of Node.JS Applications on Amazon Elastic Containers

    Let’s see the output for JSON response:

    JSON response from Web Server
    JSON response from Web Server

    Now for the HTML:

    HTML response from Web Server
    HTML response from Web Server

    Looks good. We can use this method to serve API requests using JSON or serve webpages using HTML. Also, do notice the req.url in the above code. We are returning different responses for different URLs. This is how routing works. You can check for which route the request is coming from and handle the response accordingly. Feel free to use switch case here when the number of routes increases. I hope you get a good idea of how the web server works now.

    So far, we have learned what a web server works are and how they work. We also created our web server with routing and the ability to serve multiple formats. That’s it for today’s lesson. Let me know if this was helpful in the comments below.

    You can find this lesson coding in our repository.

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    PHP February 3, 2020

    Top 6 Features of PHP 7.4 – Explained with Examples

    PHP 7.4 is a minor version, but it includes plenty of new features. Here I show you the top 6 of them with examples. They can make a significant effect on your PHP development process.

    If Trello became too small for you.

    September 30, 2016

    3. Express.js Lessons. Templating with EJS: Layout, Block, Partials

    December 16, 2016

    Enhancing Online Reputation Management in Hospitals: A Guide

    August 27, 2025

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    React Lesson 4: Homework. Decorators and Mixins

    JavaScript December 19, 2019

    DevOps Overview: Rethinking How Development and Operations Work

    Job August 26, 2019

    Effective Strategies for Generating B2B Leads via Podcasting

    B2B Leads December 6, 2024

    Sass vs. Less: Which CSS Preprocessor to Choose in 2019?

    CSS July 2, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Flask

    Integrate LDAP Authentication with Flask

    JavaScript

    Finding the Best Way to Learn JavaScript

    JavaScript

    Getting started with Next.js

    Most Popular

    Unlocking Organizational Growth: The Crucial Role of Recruitment

    Recruitment

    Facebook Ads vs Google Ads: Which Works Best for Home Services?

    Home Services Marketing

    Securing Node.js Applications with JWT and Passport.js

    Express.js
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.