Language: EN

tutorial-nodejs-montar-servidor

Basic Node.js Tutorial- How to Set Up an HTTP Server

In this post, we’ll see how to install Node.js, the popular server-side technology. If you still don’t know what Node.js is, we recommend reading the previous post What is Node.js and why you should be using it.

We will also look at the basics of how Node.js works by setting up a small web server, which for now will simply return the well-known “Hello World”, typical of any computer science introductory tutorial.

Of course, as we mentioned earlier, Node.js is much more than a server, and in the future we will see many more features and functionalities. But, as an example, it serves as an excuse to present the basics of Node.js.

How to install Node.js

Currently, installing Node.js is really easy. There are packages and installers for both Windows, Linux, and Mac, and it is also available as a container for Docker. In most cases (except for some Linux distributions) the installation process consists of downloading and running the installer.

In the case of Windows, simply download and run the installer.

tutorial-nodejs-montar-servidor-0

We make sure to have the option to add Path marked. This allows calling the Node.js executables (node and npm) from any folder, without having to write the full path to the executable (e.g.: C:\program files(x86)..etcetc..\node.exe).

tutorial-nodejs-montar-servidor-1

To check that we have installed it correctly, we open a command prompt, and write:

node --version

We should get the installed version of Node.js.

tutorial-nodejs-montar-servidor-2

To start the interpreter, simply write

node

Now if we enter JavaScript commands, for example, 2+2, we will see that Node.js processes the commands, returning 4 in our example.

tutorial-nodejs-montar-servidor-3

Very nice, but terribly uninteresting. We better improve this right now.

Running a JavaScript File

Logically, we are not going to want to enter our code in the interpreter, but we will want to save it in one or more files. Let’s see how to run a JavaScript file from Node.js.

For the sake of organization, we are going to create a folder for our projects and a folder for each project. It is not strictly necessary for Node.js to work, but it is the minimum to keep our projects organized.

In this way, we create a folder, for example in your Documents folder or in C:, and call it NodeJs (or ProyectosNodeJs, or whatever you want).

Inside this folder, we are going to create a new folder for our first Hello World project. We will call this folder ‘hola_mundo’ (very original).

Inside this folder, we create a file called ‘hello.js’, and inside it we copy the following content,

// Show text in the console
console.log("Hello World");

Which simply displays the text “Hello World” in the console. Now, we run this file with Node.js with the following command,

node hello.js

We will see that Node.js executes the file, displaying “Hello World” on the screen.

tutorial-nodejs-montar-servidor-4

We now know how to run code from a JavaScript file. Although it is still not particularly interesting, since all the code is running on the server. Let’s improve this by responding to HTTP requests made from a client.

Creating a Simple Server in Node.js

We continue with our simple Hello World example in Node.js, setting up a server that listens for HTTP GET requests on a port (for example 8080), and responds to the request with our message ‘Hello World’.

To do this, we modify our hello.js file with the following content.

// Load the HTTP module
var http = require('http');

// Set up an HTTP response for all requests
function onRequest(request, response) {
  console.log("Request Received.");
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("Hello World");
  response.end();
}

var server = http.createServer(onRequest);

// Listen on port 8080
server.listen(8080);

// Put a message in the console
console.log("Server running at http://localhost:8080/");

We start our very simple web server with the same command as before,

node hello.js

And we verify that Node.js responds correctly indicating that it is accepting requests,

tutorial-nodejs-montar-servidor-5

Now, in a web browser, we call the address localhost:8080, and we will see that Node.js returns a simple HTTP response that contains ‘Hello World’, which the browser picks up and renders for us.

tutorial-nodejs-montar-servidor-hola-mundo

We also see in the command prompt that Node.js indicates with ‘Request Received’, indicating that a connection has been established.

tutorial-nodejs-montar-servidor-6

Therefore, we see that we have successfully set up a very simple web server with Node.js. Now we could serve a file (html, css, js), data loaded from a database, or even turn on/off a light, or move a robot with a microprocessor like Arduino.

Isn’t this starting to get more interesting?

The package.son file

So far, we have saved the file in a folder and launched the file with the Node.js executable. However, when working on a project, it is customary to have a package.son file.

This file stores the most important data and configuration of the App we are developing, such as the name, version, dependencies, etc.

We can quickly create this file with the Node Package Manager (npm). To do this, within our project folder we run the command

npm init

NPM asks us a series of questions to configure our App. We can modify this data later. For now, for this example, just pressing ENTER in all the questions is sufficient.

tutorial-nodejs-montar-servidor-7

In the folder of our project, the package.son file is created, with the data we have entered.

Now let’s modify this file to indicate that the entry point to our App is our hello.js file. To do this, we modify the contents of the package.son file with the following.

{
  "name": "hola_mundo",
  "version": "1.0.0",
  "description": "",
  "main": "hello.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
   "start": "node hello.js"
  },
  "author": "",
  "license": "ISC"
}

Finally, we can start our application simply by writing,

npm start

tutorial-nodejs-montar-servidor-8

These are just a few brushstrokes on the use of Node.js. In future posts, we will frequently use Node.js, and we will learn to connect it with a database, develop a REST API, and use it in robotics and IoT projects.