Developing Web Applications Using Node.js Part 1

Опубликовано - Последнее изменение:

Compared to other Web frameworks like Flask or Laravel, Node.js is a low-level framework. Because of this, developers need to concentrate more on each part of the application. Node was designed and implemented to have a non-blocking, asynchronous environment. Using the async paradigm Node is a perfect fit for data-intensive real time (DIRT) applications.

Creating an echo server

When creating an echo server, we first need to make sure we have node installed. This can be checked using the following commands on a Unix machine:

    greg@earth:~$ node -v
    greg@earth:~$ nodejs -v

If we don't get a similar input when running these commands, node is probably not installed. For installation, please refer to this article.

Node has an HTTP module, allowing it to be used to create a new HTTP server that accepts requests from clients (browsers, other applications). 

var http = require("http");

var SEPARATOR =   "---------------------------------------";
var NEW_REQUEST = "              NEW REQUEST";

var echo_server = http.createServer(function(request, response){
        console.log("HTTP Version:" + request.httpVersion);

        console.log("HEADERS: User Agent: " + request.headers["user-agent"]);

        // Since the request and response are streams,
        // We can pipe the request into the response stream
        // With this creating an echo server



We can reference the HTTP module using the require("http") construct. The module can create a new HTTP server for us using the createServer() method. This method needs a callback function that is invoked for each request coming to the server.

The anonymous function has two parameters: the incoming HTTP request, and the response that will be sent back to the client. We log information coming from the client, such as the HTTP version and the user-agent from HTTP headers.

Because the request and response are both implemented as streams in node, all we need to do to get the echo functionality of the server is pipe the request into the response stream.

The echo server can be started using:

    greg@earth:~/Development/node_echo$ node echo_server.js

Requests can come from a browser or a Unix command like curl (it can be used to check how the echo server is working).

If we use curl, the command should be the following:

    greg@earth:~$ curl -d "hello awesome node echo server \                         
    > " http://localhost:13333
    hello awesome node echo server 

On the server side the details of the request can be seen:

                  NEW REQUEST
    HTTP Version:1.1
    HEADERS: User Agent: curl/7.35.0

If the request comes from a browser the details logged by the server are different:

                NEW REQUEST
    HTTP Version:1.1
    HEADERS: User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

The code for the echo server can be found on GitHub, under node_projects repository.

Подпишитесь на еженедельные обновления прямо сейчас

Оставайтесь в курсе событий с помощью лучших статей сообщества Freelancer. Подпишитесь прямо сейчас, чтобы еженедельно получать лучший контент в сфере дизайна, разработки и фриланса.

Опубликовано 2 марта, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Следующая статья

Tips for a Fledgling Freelance Designer