Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Beginners

    A Roundup Review of the Best Deep Learning Books

    Development

    Enhancing Software Development: The Crucial Role of Version Control

    Startups

    Why Startups Fail? Part 1

    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, November 12
    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:  Markdown Cheat Sheet: Definitive Guide to Markdown + Markdown Resources

    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:  Mastering N-API and Native Modules in Node.js

    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
    LinkedIn December 4, 2024

    Strategies for Consistent Engagement with LinkedIn Prospects

    To achieve consistent engagement with LinkedIn prospects, employ targeted content sharing, personalized outreach, and regular interaction through comments and messages. Utilizing analytics to refine strategies enhances visibility and fosters meaningful connections.

    Outdated MVP

    November 3, 2016

    Mastering B2B Lead Generation: Your Complete Guide

    December 20, 2024

    Programming Patterns. SOLID principle

    January 31, 2017

    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

    How And When To Debounce And Throttle In React

    JavaScript May 14, 2023

    NLP Preprocessing using Spacy

    Machine Learning April 5, 2023

    Mastering Project Management: Effective Use of Gantt Charts

    JavaScript December 5, 2024

    Full Node.js Course

    Programming November 24, 2016

    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
    Recruitment

    Overcoming Recruitment Challenges in International Hiring

    Recruitment

    Enhancing Employee Retention: The Critical Role of Recruiters

    JavaScript

    Fortune 500 top hiring trends in 2019. How top companies attract best talents?

    Most Popular

    Build Real-World React Native App #9 : Implementing Remove Ads Feature

    JavaScript

    5 Effective DevOps Practices You Must Follow

    Tips

    Effective LinkedIn Outreach: Proven Strategies for Prospects

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

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