Building Basic Node.js Applications: Console and Web Examples

Learn the fundamentals of Node.js application development with this introductory guide. This tutorial covers creating simple console-based applications and building a basic web server using the `http` module, providing a foundational understanding for further Node.js development.



Building Basic Node.js Applications

Node.js can be used to create both console-based and web-based applications. This guide demonstrates building a simple Node.js web application using the `http` module. It explains the fundamental steps of creating a server and handling HTTP requests and responses.

Node.js Console-Based Application

A simple console-based application simply uses the `console.log()` method to print output to the console.


console.log('Hello from Node.js!');

Node.js Web-Based Applications

A basic Node.js web application consists of three main parts:

  1. Import Required Modules: Use `require()` to load necessary modules (like `http`).
  2. Create Server: Create an HTTP server instance using `http.createServer()`.
  3. Handle Requests and Responses: The server's callback function handles incoming requests and sends responses.

Creating a Simple Web Server

Let's build a simple web server that returns "Hello, World!". (Note that you will need to have Node.js installed to run this application.)

Step 1: Import the `http` Module


const http = require('http');

Step 2: Create and Start the Server


const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!\n');
});

server.listen(8081);
console.log('Server running at http://127.0.0.1:8081/');

This creates a server that listens on port 8081. The callback function handles incoming requests, sending a "Hello, World!" response. The console message indicates the server is running. You can then access the server in a browser at `http://127.0.0.1:8081/`.