Getting Started with Node.
js: Creating a Simple Web Server
This document will guide you through the process of setting up and running a basic web
server using Node.js. This is a fundamental first step for building any web application with
Node.js.
Prerequisites
Before you begin, make sure you have the following software installed on your machine:
Node.js: The JavaScript runtime environment. You can download it from the official
Node.js website.
npm: The Node.js package manager, which is installed automatically with Node.js.
Step-by-Step Guide
Step 1: Initialize Your Project
First, create a new directory for your project and navigate into it using your terminal or
command prompt.
mkdir my-first-server
cd my-first-server
Next, initialize a new Node.js project. This command creates a package.json file to manage
your project's dependencies and metadata.
npm init -y
The -y flag answers "yes" to all the default questions, making the process faster.
Step 2: Write the Server Code
Create a new file named server.js in your project directory. Open this file in your preferred
code editor and add the following code:
// Import the 'http' module, which is a core Node.js module
// for creating HTTP servers.
const http = require('http');
// Define the hostname and port for the server.
const hostname = '127.0.0.1'; // This is localhost
const port = 3000;
// Create the server instance.
const server = http.createServer((req, res) => {
// Set the HTTP status code to 200 (OK).
res.statusCode = 200;
// Set the HTTP header to indicate the response content type.
res.setHeader('Content-Type', 'text/plain');
// Send a response to the client.
res.end('Hello, World!\n');
});
// Start the server and listen for incoming requests on the specified port.
server.listen(port, hostname, () => {
// This callback function runs when the server is successfully started.
console.log(`Server running at http://${hostname}:${port}/`);
});
Step 3: Run Your Server
To start your server, go back to your terminal and run the server.js file using the node
command.
node server.js
You should see the message Server running at http://127.0.0.1:3000/ printed in your
terminal. This means the server is running and listening for requests.
Open your web browser and navigate to http://127.0.0.1:3000/. You should see the text
"Hello, World!" displayed on the page.
Explanation of the Code
const http = require('http');: This line imports the built-in http module, which
contains the functionality needed to create an HTTP server.
http.createServer(...): This method creates a new server object. It takes a single
argument, which is a function that will be called every time a request is received.
(req, res) => { ... }: This is the request handler function. It receives two objects: req
(the request object) and res (the response object).
res.statusCode = 200;: This sets the HTTP status code. A status of 200 means the
request was successful.
res.setHeader('Content-Type', 'text/plain');: This sets a header on the response,
telling the browser that the content it's about to receive is plain text.
res.end('Hello, World!\n');: This sends the response body to the client and signals
that the response is complete.
server.listen(...): This method starts the server and makes it listen for connections on
the specified hostname and port.
Next Steps
Now that you have a basic server running, you can explore more advanced topics like:
Serving HTML files: Instead of plain text, serve a full HTML page.
Handling different routes: Respond with different content based on the URL the user
requests (e.g., /about, /contact).
Using frameworks: Learn how to use popular frameworks like Express.js to simplify
server creation.