So, why would you want to write your own web server? If you find that you just need an easy way to serve some static web pages on your own computer for development and testing purposes and you've struggled with setting up and configuring off-the-shelf web servers, then this could be a great solution.
Download and Install Node.js
To get started, go to the official Node.js website and click the download link. Choose the Windows Installer, Mac Installer, or Source Code if you're not on Mac or Windows and then download Node.js and follow the installation instructions for your computer.
Middleware, like plugins that add additional features to a software package, are building blocks that bring your Node.js application to life faster. Our web server uses the Connect middleware for the heavy lifting.
To install Connect, we'll need the Node Package Manager (NPM). On Linux, start a new shell session, on OS X go into the terminal, and on Windows bring up the command prompt. Then, run the command
npm install connect to download and install Connect.
NOTE: If you installed the most recent Node.js version, NPM should have come with it. If you get an error message from the command above that indicates your computer can't find NPM, you can download it from the NPM website and then try again to install Connect.
Create a Sample Web Page
NOTE: If you already have an HTML file you'd like to work with, you can skip this step.
Open your favorite text editor or IDE and create a file called test.html with the following code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Hello From Node.js!</title>
<p>Hello from Node.js!</p>
Create the Node.js Web Server
In your text editor or IDE, create a file called NodeServer.js with the following lines:
var connect = require('connect');
Important: Make sure you put the test.html file (or your own HTML file if you had one) in the same directory on your computer as the NodeServer.js file.
Test Your Web Server
Go back into your shell, terminal, or command prompt window and navigate to the directory with the NodeServer.js file. Run the command
node NodeServer.js to start your new web server.
To test everything out, open your web browser and go to http://127.0.0.1:8080/test.html (be sure to replace test.html in the address with your HTML file's name if you used your own file).
To stop your web server, simultaneously press the Control and C keys on your keyboard in Linux and Windows or the Command and C keys in OS X.
And, just like that, without any configuration files, complex network setups, or other installation hassles, you've created a web server that you can start up anytime you want to deliver web pages right from your very own computer.