1. Building Your First Application

Creating your first application in Node.js is an exciting way to explore how this powerful JavaScript runtime works. In this guide, you'll build a simple web server that responds to client requests. This foundational exercise will introduce you to the core concepts of Node.js, such as handling HTTP requests, using modules, and running your server locally.


2. Prerequisites

Before starting, ensure you have the following:

  • Node.js installed: Download and install Node.js from nodejs.org.
  • Code editor: Use an editor like Visual Studio Code (VS Code) for writing your code.

  • 3. Setting Up the Project

    1. Create a Project Directory

    First, create a new directory for your application and navigate into it using the terminal.

    				
    					mkdir first-node-app
    cd first-node-app
    
    				
    			

    2. Initialize the Project

    Initialize a new Node.js project using npm. This will create a package.json file to manage your project's dependencies.

    				
    					npm init -y
    
    				
    			

    The -y flag skips the setup prompts and generates a default package.json file.


    4. Creating the Server

    1. Create the Main File

    Create a file named app.js in the project directory.

    				
    					touch app.js
    
    				
    			

    2. Write the Server Code

    Open app.js and add the following code to create a simple HTTP server:

    				
    					// Import the HTTP module
    const http = require('http');
    
    // Create the server
    const server = http.createServer((req, res) => {
      // Set the response header
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      
      // Send the response message
      res.end('Hello, World! Welcome to my first Node.js application.');
    });
    
    // Start the server on port 3000
    const PORT = 3000;
    server.listen(PORT, () => {
      console.log(`Server is running on http://localhost:${PORT}`);
    });
    
    				
    			

    Explanation:

  • http.createServer() creates an HTTP server that listens for requests.
  • res.writeHead(200, ...) sends a status code of 200, indicating a successful response.
  • res.end() ends the response and sends the message to the client.
  • server.listen() starts the server on the specified port.

  • 5. Running the Application

    To run your application, use the following command in your terminal:

    				
    					node app.js
    
    				
    			

    You will see the following message in the terminal if everything is set up correctly:

    				
    					Server is running on http://localhost:3000
    
    				
    			


    6. Testing the Application

    1. Open Your Browser

    Navigate to http://localhost:3000 in your web browser.

    2. View the Output

    You should see the message:

    Hello, World! Welcome to my first Node.js application.


    7. Customizing the Application

    You can enhance the application by adding dynamic content or handling different routes:

    				
    					const http = require('http');
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/html' });
    
      if (req.url === '/') {
        res.end('<h1>Welcome to My Node.js App</h1>');
      } else if (req.url === '/about') {
        res.end('<h1>About Us</h1><p>This is a simple Node.js application.</p>');
      } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 - Page Not Found');
      }
    });
    
    const PORT = 3000;
    server.listen(PORT, () => {
      console.log(`Server is running on http://localhost:${PORT}`);
    });
    
    				
    			

    Explanation:

  • req.url checks the requested URL path and serves different content based on the route.
  • 404 responses are returned for unknown routes.

  • 8. Adding NPM Packages

    Node.js applications often use third-party packages. Let's install nodemon, a tool that automatically restarts the server when code changes:

    1. Install Nodemon

    				
    					npm install -g nodemon
    
    				
    			

    2. Run the Server with Nodemon

    				
    					nodemon app.js
    
    				
    			


    9. Conclusion

    Congratulations! You've successfully built and run your first Node.js application. Along the way, you learned how to:

  • Set up a Node.js project using npm.
  • Create and run a basic HTTP server.
  • Customize server responses based on routes.
  • Use tools like nodemon for efficient development.
  • This foundational project is the first step toward building more complex, scalable applications with Node.js. Keep exploring modules, APIs, and frameworks like Express to enhance your skills further.

    ×