Basic Web Server

Crating a basic Web Server.


Starting up Steps:

  • Create a directory with a Readme.txt file
  • Initialize a Git Repo (Optional)
  • CD to the directory and check node using: “npm -v”

Create Package.jason

In the project directory create the file: package.jason by executing the following commands in the terminal. ” npm init ” and provide the required information or just hit enter when you have a question to select the default value. Now open the new created file with Atom. The code should looks like:

Server.js File

Create a new file and name it: “server.js
Now go to the nodejs.org website and click on the About page. There you will find an extreme basic example of a “Web Server”, copy the basic code and paste on the server.js file.  The code should look like:

Testing the server

Now in the terminal type the command: ” node server.js ” and you should see the response  ” Server running at http://127.0.0.1:3000/ ”   NOTE: you can start the sever also using the command ” npm start

The address 127.0.0.1 is you local host and the 3000 is the port that is been used by the server. now lest check this on the browser.

In the browser type: localhost:3000 and hit Enter, if successful the browser should load a web page with the text: ” Hello World

Congratulations you create your first Node Project, a basic web server, but we are not done yet. this sever is serving text messages to the browser, in the real life this not happen, web servers serve HTML pages.

Serving a HTML Pages.

To do this we need to modify the code in the file: “server.js” and it should look like:

This is build to serve HTML pages, however this is just for exercise, in future projects we will be using a different code to crate and run the Node.js Server, in the industry is common practice to use Express and other tools to make this more simple, but it was important that you see the code without frameworks so you can see how it works.

Now you can start the server again and request some HTML Sites, I create a whole site with pages of some singers that I was lisenning while I was creation this project, find all the code and files in GitHub: Node.js-basic-Web-Server.

Here is a picture of the site when the server running and serving multi page sites.

The source code for the web pages is on the GitHub Repository too.



Copyright 2017. All rights reserved.

Posted May 8, 2017 by Edmundo in category "Node