Create a First App with Node.js 

Creating your first Node.js application is a rite of passage for many web developers. Node.js allows you to run JavaScript on the server, giving you the power to build scalable network applications using the same language you use in the browser. In this guide, we will build a basic HTTP server that greets you in the browser.

Developer Tip: Node.js is built on Chrome's V8 engine, which means it executes JavaScript extremely fast. It's perfect for I/O-intensive tasks like chat apps or streaming services.

 

Steps to Create Your First Node.js App

1. Set Up a Project Directory

  • Start by creating a dedicated folder for your project. This keeps your files organized and prevents global configuration conflicts.
mkdir my-first-node-app
cd my-first-node-app
Best Practice: Always use lowercase letters and hyphens for project folder names. This avoids issues with case-sensitive file systems and matches standard naming conventions in the JavaScript ecosystem.

2. Initialize a Node.js Project

  • Before writing code, you need to initialize your project to create a package.json file.
npm init -y
  • The -y flag stands for "yes"—it skips the interactive questions and creates a manifest file with default values. This file tracks your project's dependencies and metadata.

3. Create the Application File

  • Create the main entry point for your server. While you can name this anything, app.js or index.js are the industry standards.
touch app.js
Developer Tip: If you are on Windows and touch doesn't work, you can simply use echo "" > app.js or create the file manually in VS Code.

4. Write the Code

  • Open app.js in your favorite code editor (like VS Code) and add the following logic:
const http = require('http');

// Define the server logic
const server = http.createServer((req, res) => {
  // Set the response HTTP status and content type
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  
  // Send the body of the response
  res.end('Hello, Node.js!');
});

// Define the port and start listening
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});
Common Mistake: Forgetting to call res.end(). If you don't call this method, the browser will keep waiting for the server to finish, and the page will eventually time out.

5. Run the Application

  • Switch back to your terminal and tell Node.js to execute your file:
node app.js
  • Once the server is running, open your web browser and go to http://localhost:3000.
Watch Out: If you make changes to your code in app.js, you must stop the server (Ctrl+C) and run node app.js again to see the updates.

6. Output

  • Browser: You will see the plain text:
Hello, Node.js!
  • Terminal: You will see the confirmation message:
Server is running at http://localhost:3000

 

Explanation of Code

1. http Module

  • The require('http') statement imports Node's built-in HTTP module. This module contains the necessary logic to handle network protocols without needing to install external libraries.

2. createServer Method

  • This method takes a "callback" function that runs every time a request hits your server. It provides two vital objects: req (the Request from the user) and res (the Response you send back).
Developer Tip: In a real-world app, you would use the req.url property to check which page the user is trying to visit (e.g., /home vs /contact).

3. Response Methods

  • res.writeHead: Communicates with the browser to let it know the request was successful (Status 200) and that the data being sent is plain text.
  • res.end: This finalizes the response. You can pass the data you want to display directly into this method.

4. listen Method

  • Servers need to "sit and wait" for traffic. The listen method assigns your server to a specific port (3000) on your local machine.
Watch Out: If you get an error saying "EADDRINUSE," it means another program is already using port 3000. You can change the port number in your code to 3001 or 4000 to fix this.

 

Summary

Congratulations! You've just moved from being a consumer of the web to a creator of web infrastructure. By building this basic HTTP server, you've learned how Node.js manages requests and responses. From here, most developers move on to frameworks like Express.js to build more complex APIs and full-stack web applications. Happy coding!