Creating Your First Node.js Server
# CHAPTER 5
Creating Your First Node.js Server
1. Introduction
When you build a website with HTML, you rely on software like Apache or Nginx to act as the web server. Node.js is different. In Node.js, *you write the web server yourself*. Using the built-inhttp module, we can instruct our computer to listen for incoming internet traffic, process it, and send a response back. In this chapter, we will build a pure Node.js web server from scratch.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use the built-in
httpmodule to create a server.
-
Understand the
req(Request) andres(Response) objects.
- Send an HTTP status code and response headers.
- Listen on a specific network port.
3. Beginner-Friendly Explanation
Imagine you are starting a drive-thru restaurant. You need three things:- 1. The Building (The Server): You need a physical place to do business.
- 2. The Speakerbox (The Port): You need a specific frequency where customers can talk to you.
- 3. The Cashier (The Callback Function): When a customer talks into the speaker (a Request), the cashier figures out what they want, and hands them food (the Response).
In Node.js, we write a few lines of code to create the building, assign the speakerbox to Port 3000, and write a function that hands back data to anyone who visits http://localhost:3000.
4. Step 1: Importing the HTTP Module
Node.js comes with several core modules out of the box. You do not need tonpm install them. The http module contains all the networking logic required to build a server.
Create a file named server.js and add:
5. Step 2: Creating the Server
We use thecreateServer method. It takes a callback function with two critical arguments:
-
req: The incoming Request (what the user asked for).
-
res: The outgoing Response (what we will send back).
6. Step 3: Listening on a Port
The server exists in memory, but it isn't listening for traffic yet. A computer has thousands of "Ports" (doors). Web traffic usually enters through Port 80 or 443. For local development, we typically use Port 3000, 5000, or 8080.7. The Complete Code
Here is your completeserver.js file:
To run this: Open your terminal and type node server.js. Then visit http://localhost:3000/api/users in your browser.
8. Backend Workflow: Why Pure Node.js is Painful
Look at the code above. To handle just two URLs, we had to write messyif/else statements. If we had 100 APIs, our code would be 1,000 lines of if/else spaghetti. Furthermore, extracting JSON data from a POST request in pure Node.js requires reading complex data streams manually.
This is why professional developers almost *never* use the raw http module to build full applications. We use frameworks.
9. Best Practices
-
Never Hardcode Ports: In production, companies like Heroku or AWS assign random ports dynamically. You should always use environment variables.
const PORT = process.env.PORT || 3000;. This says: "Use the server's requested port, but if we are on my local laptop, use 3000."
10. Common Mistakes
-
Forgetting
res.end(): If you forget to callres.end()inside your server block, the server will accept the request but never finish responding. The user's web browser will show a spinning loading wheel forever until it eventually times out.
11. Exercises
-
1.
Explain the roles of the
req(Request) andres(Response) objects in thehttp.createServercallback function.
12. Coding Challenges
-
Challenge: Modify the
server.jsfile to add a new route:/about. If a user visits/about, return an HTML string:<h1>About Us</h1>. Make sure to change the Content-Type header totext/html.
13. MCQs with Answers
Which built-in Node.js module is required to create a web server?
What happens if you forget to include res.end() in your server response logic?
14. Interview Questions
-
Q: Explain the purpose of
process.env.PORTwhen defining a server's listening port.
-
Q: Why do developers rarely use the raw
httpmodule to build large-scale REST APIs? What specific challenges arise?
15. FAQs
Q: Can I run multiple Node.js servers on my laptop at the same time? A: Yes, as long as they are assigned to different ports. You can have one API running on Port 3000, and a different API running on Port 4000. If you try to run both on 3000, Node will throw anEADDRINUSE (Address already in use) error.
16. Summary
In Chapter 5, we became server engineers. By utilizing Node's built-inhttp module, we established a listener on Port 3000. We intercepted incoming requests (req), manipulated the HTTP Headers to specify our data format (Plain text or JSON), and finalized the connection using res.end(). However, we also identified the limitations and messy routing logic required when using pure Node.js.
17. Next Chapter Recommendation
To fix the messyif/else routing of pure Node.js, we need a framework. Proceed to Chapter 6: Introduction to Express.js, the industry standard tool for building APIs.