This project is a lightweight, modular web server built with Node.js. It demonstrates core concepts of server-side programming without relying on frameworks, focusing on:
- Event-driven architecture using Node.js
EventEmitter
. - Asynchronous file handling with
fs/promises
. - Dynamic MIME type handling for serving static and dynamic files.
- Modular code organization with dedicated utilities for logging and file serving.
- Static File Serving: Supports serving files (CSS, JavaScript, images, etc.) from a
public
directory. - Dynamic Routing: Dynamically resolves routes for
.html
files in aviews
directory. - Custom Logging: Logs requests and errors into separate log files (
reqLog.txt
,errorLog.txt
) using a unique ID for each log entry. - 404 Handling: Serves a custom
404.html
page for invalid routes. - Redirects: Handles specific redirects with status code
301
. - MIME Type Support: Supports a wide range of MIME types, including
text/html
,application/json
, and various image formats.
├── logs/ # Directory for generated log files
| ├── errorLog.txt # Errors logs text file
| └── reqLog.txt # Requests logs text file
├── node_modules/ # Node modules
├── public/ # Directory for static assets (CSS, JS, images, etc.)
| └── css/ # CSS stylesheets
| └── img/ # Images directory
└── src/ # App source directory
├── views/ # Directory for HTML files
├── server.js # Main server file
├── logEvents.js # Logging utility
└── serveFile.js # File serving utility
-
Clone the repository:
git clone https://github.com/MartinXCVI/node-web-server
-
Navigate to the project directory:
cd node-web-server
-
Install dependencies:
npm install
-
Start the server:
npm start
-
Open your browser and navigate to:
http://localhost:3500
PORT
: Define the port number for the server. Defaults to3500
if not specified.
- Logs every incoming request (URL and method) to
reqLog.txt
. - Serves files from the
public
directory if they exist and match the request. - For dynamic routes:
- Serves HTML files from the
views
directory. - Redirects or serves a
404.html
page if the file doesn't exist.
- Serves HTML files from the
- All logs are timestamped and include a unique ID.
- Logs are written to the
logs
directory, with separate files for requests and errors.
- Errors encountered while serving files are logged in
errorLog.txt
. - A generic
500 Internal Server Error
response is sent if file serving fails.