A C C R E T E

How to Set Up a Simple Node.js Server in 5 Minutes

Are you new to Node.js and want to get started quickly? To set up Node.js server is much simpler than you might think. This guide will walk you through the process step-by-step, so you can have your first server up and running in just five minutes.

Why Node.js?

Node.js is a powerful, event-driven JavaScript runtime built on Chrome’s V8 engine. It allows you to run JavaScript on the server side, making it a popular choice for building fast, scalable network applications.

Read in depth about What is a REST API?

What You’ll Learn

  • How to install Node.js
  • Setting up a simple server
  • Creating a server.js file
  • Running your server locally
  • Handling basic GET requests

Let’s dive in!
Server concept illustration

Step 1: Installing Node.js

Before setting up your server, you need to install Node.js on your machine. Follow these steps:

  1. Download Node.js: Visit the Node.js official website and download the LTS (Long-Term Support) version for your operating system.
  2. Install Node.js: Run the downloaded installer and follow the instructions. Make sure to install the necessary tools like npm (Node Package Manager) that come bundled with Node.js.
  3. Verify Installation: After installation, open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and type the following commands to check if Node.js and npm are installed correctly:
    node -v
    npm -v

    These commands should return the version numbers of Node.js and npm respectively.

Step 2: Setting Up a Simple Server

Now that you have Node.js installed, let’s set up a simple server.

  1. Create a New Directory: Open your terminal and create a new directory for your project.
    mkdir my-first-node-server
    cd my-first-node-server
  2. Initialize a Node.js Project: Run the following command to create a package.json file, which will keep track of your project’s dependencies and scripts.
    npm init -y

Step 3: Creating the server.js File

  1. Create the server.js File: Inside your project directory, create a new file named server.js.
    touch server.js
  2. Write Basic Server Code: Open server.js in your text editor and add the following code:
    const http = require('http');
    
    const hostname = '127.0.0.1';
    const port = 3000;
    
    const server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Hello, World!\n');
    });
    
    server.listen(port, hostname, () => {
        console.log(`Server running at http://${hostname}:${port}/`);
    });

Step 4: Running the Server Locally

  1. Run Your Server: Go back to your terminal, ensure you’re in the project directory, and run the server with the following command:
    node server.js
  2. Access Your Server: Open your web browser and go to http://127.0.0.1:3000/. You should see “Hello, World!” displayed on the page.

Step 5: Handling Basic GET Requests

To make your server more interactive, let’s handle GET requests and respond with different messages based on the URL.

  1. Modify server.js to Handle GET Requests:
    const http = require('http');
    
    const hostname = '127.0.0.1';
    const port = 3000;
    
    const server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
    
        if (req.url === '/') {
            res.end('Welcome to the homepage!\n');
        } else if (req.url === '/about') {
            res.end('Learn more about us on this page.\n');
        } else {
            res.statusCode = 404;
            res.end('Page not found.\n');
        }
    });
    
    server.listen(port, hostname, () => {
        console.log(`Server running at http://${hostname}:${port}/`);
    });
  2. Restart the Server: Stop the current server by pressing Ctrl+C in the terminal. Then, run it again with node server.js.
  3. Test Different Routes: Visit http://127.0.0.1:3000/, http://127.0.0.1:3000/about, and a non-existent route like http://127.0.0.1:3000/contact to see how your server handles different URLs.

Conclusion

Congratulations! You’ve just set up a basic Node.js server and handled simple GET requests. This foundation will help you build more complex web applications in the future. Keep experimenting with Node.js, and you’ll discover its full potential in creating powerful server-side applications.

Happy coding!

Find an agent now

Telephone

+91 079 232 13063

Time Schedule

Office Time

Mon - Fri: 9:00 - 18:00