Skip to content

Node.js First Application

Before building our “Hello, World!” application with Node.js, let’s understand the fundamental parts of a simple Node.js web server. A basic Node.js application typically involves these steps:

  1. Import required modules: Use the require function (for CommonJS modules, the default in traditional Node.js) or import statement (for ES modules) to load necessary Node.js core modules or third-party libraries.
  2. Create an HTTP server: Instantiate a server object capable of listening for incoming client requests, similar to web servers like Nginx or Apache.
  3. Handle requests and send responses: The server needs logic to process incoming HTTP requests (e.g., from a web browser) and send back appropriate HTTP responses.

We use the require function to load Node.js’s built-in http module. This module provides classes and functions for creating HTTP servers and clients. We store the module’s exports in a constant named http.

const http = require('http');

Note: Modern JavaScript often uses const for variables that won’t be reassigned and let for variables that might be. While var still works, const and let offer better scope control and are generally preferred.

Next, we use the http.createServer() method. This method takes a callback function (often called a request listener) that will be executed each time the server receives a new request. The callback function receives two arguments: a request object (containing information about the incoming request) and a response object (used to send data back to the client).

Inside the callback, we set the HTTP status code to 200 (OK) and the Content-Type header to text/plain using response.writeHead(). Then, we send the response body “Hello World\n” using response.end(). Finally, we chain the .listen() method to make the server start listening for connections on a specific port (e.g., 3000) and hostname (e.g., ‘127.0.0.1’ for localhost).

const server = http.createServer((request, response) => {
// Set the response HTTP header with HTTP status and Content type
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Send the response body "Hello World"
response.end('Hello World\n');
});
const port = 3000;
const host = '127.0.0.1';
server.listen(port, host, () => {
// Log a message to the console once the server starts listening
console.log(`Server running at http://${host}:${port}/`);
});

This code creates an HTTP server that listens on port 3000 on your local machine. Using port 3000 is a common convention for local development servers, avoiding potential conflicts with services using default ports like 80 or 8080.

Step 3: Running and Testing the Application

Section titled “Step 3: Running and Testing the Application”

Save the complete code (Steps 1 and 2 combined) into a file named server.js:

const http = require('http');
const server = http.createServer((request, response) => {
// Set the response HTTP header with HTTP status and Content type
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Send the response body "Hello World"
response.end('Hello World\n');
});
const port = 3000;
const host = '127.0.0.1'; // Equivalent to 'localhost'
server.listen(port, host, () => {
// Log a message to the console once the server starts listening
console.log(`Server running at http://${host}:${port}/`);
});

Now, open your terminal or command prompt, navigate to the directory where you saved server.js, and run the application using the Node.js runtime:

$ node server.js

You should see the following output in your console, indicating the server has started successfully:

Server running at http://127.0.0.1:3000/

Open your web browser and navigate to http://127.0.0.1:3000/ (or http://localhost:3000/). You should see the text “Hello World” displayed on the page.

Congratulations! You’ve successfully created and run your first basic Node.js HTTP server. This server responds to all requests with the same simple message. Real-world applications typically use frameworks like Express.js or Fastify to handle routing, middleware, and other complex tasks more easily, but understanding this fundamental example is crucial.