An absolute starter’s guide to Node.js for beginners

JavaScript has always been a client-side programming language. While almost everything on the client side is written in JavaScript, on the other side, code on the server side is a combination of various traditional languages like PHP, Java, and Ruby etc.

Think, how much simple web developers’ life would be, if a single language is used on both client and server sides. That’s why; the concept of server-side JavaScript came into existence. In this article, I’ll introduce you to a great way of implementing JavaScript on server-side: Node.js.

Node.js for beginner

Let’s get started!

 

What is Node.js?

Node.js is an open-source, lightweight and efficient server-side JavaScript platform, designed to build complex event-driven network applications easily. Unlike other traditional server-side languages such as PHP, Ruby, Python etc, which use multithreaded execution, Node.js makes use of an event-based server execution process to make an application extremely fast and scalable. Means, each and every function is asynchronous in Node.js. Although Node.js is designed with single-threaded execution in mind, but you can also take advantage of multiple cores using its child_process.fork() API.

Built on the top of Google’s V8 JavaScript engine, Node.js is influenced by and has a similar design to other systems such as the Python’s Twisted and Ruby’s Event Machine. By presenting the event loop as a language construct, it takes the event model to the next level. Where traditional models use a blocking call to start the event-loop, on the other hand, Node.js has no such start-the-event-loop call. Instead, it enters the event loop after the execution of input script and exists there until all callbacks are performed.

 

Understanding Node.js Modules

A module is the basic building block that contains a single unit of code used to construct a Node application. In other words, every JS file in Node.js is itself a module. Node.js features a simple module loading system. Modules and files in Node.js work on the concept of one-to-one correspondence.

Below is the example showing you how modules work, in which the module circle.js is loaded into foo.js that resides in the same directory. Here is the code that exists in foo.js:

var circle = require(‘./circle.js’);

console.log( ‘The area of a circle of radius 4 is ‘

           + circle.area(4));

And following is the code of circle.js:

var PI = Math.PI;

exports.area = function (r) {

  return PI * r * r;

};

exports.circumference = function (r) {

  return 2 * PI * r;

};

As you can see, for adding area() and circumference() functions to the root of foo.js, the circle.js module has added them to the exports object.

Core Modules:

Node ships with several core modules that are defined in the lib/ folder in node’s source. Node always prefer to load a core module, if its identifier is passed to require() method. For example, require(‘http’) always returns the core HTTP module, even if a file has a similar name to ‘http’.

 

File Modules:

If Node.js is not able to find the exact file name, in that case, it tries to load the required filename with .js (JavaScript text file), .json (JSON text file), or .node (compiled add-on modules) extension. A module prefixed with ‘/’ represents the absolute path to the file calling require(), while a module prefixed with ‘./’ is relative to the file. In the case of relative path, modules must be in the same directory. Without a ‘/’ or ‘./’, Node either loads a module from node_modules directory or uses a “core module”.

 

Getting Started With Node.js

 Installing Node.js:

Installing Node.js is as easy as one, two, and three! Head over to official website of Node.js; download its pre-built installer for the platform you’re using and run the installer. That’s it! Node.js is absolutely free to use and works perfectly on Windows, Linux, Mac, and Solaris operating systems.

 

Testing Installation

To check if your Node installation is successful, you need to write a simple console “Hello Everyone” program. Open your favorite editor, write the following code and save the file with name helloeveryone and .js extension.

console.log(“Hello Everyone”);

Now, execute it using the following command.

node helloeveryone.js

If the node installation is successful, then you should get “Hello Everyone” output on your screen.

 

Creating a Basic HTTP Server

Now, I’ll show you how to create a simple HTTP server with Node.js. Let’s create a new file named “server.js” in the root folder of the project and fill it with the code given below and save it.

var http = require(“http”);

var server = http.createServer(function(request, response) {

                 console.log(“Received a request”);

                 response.writeHead(200, {“Content-Type”: “text/html”});

                 response.write(“Hello Everyone”);

                 response.end();

});

server.listen(8080);

console.log(“Server is listening”);

That’s it! Let’s run and test the HTTP server that you’ve wrote. You can easily do it by typing the command shown below in a terminal window.

node server.js

If everything is fine, you’ll be able to see a message: Server is listening.

The next step is to establish a connection with server using a web browser. Open your favorite browser and direct it to http://localhost:8080. Your browser should output “Hello Everyone”. As I’ve already mentioned this is a basic HTTP server, no matter what URL you enter in the browser, you’ll get the same output like “Hello Everyone”.

Note: In my example, the server will attempt to bind to port 8080. You may face an error, in case either this port is restricted or already in use on your machine.

 

Let’s Analyze the Code:

As our server is successfully created, now we’ll analyze what’s actually happening in the above code. Let’s start with the first line of the code.

var http = require(“http”);

The require() method is used to load a particular module such as http (which ships with every Node.js installation) in the project. Where some modules are included in Node.js, others are needed to be downloaded.

var server = http.createServer(function(request, response)

In second line, in order to create the HTTP server, I’ve used createServer: one of the functions offered by the http module. Like other Node.js functions, this function also takes a callback function as a parameter. Each time a request is made to the server, this callback function is executed.

Further, this callback function takes two parameters – request, containing information regarding the request sent by client; and response, which is used to send things back to the client.

console.log(“Received a request”);

To detect a request, I’ve put this line of code into the callback function. Whenever a user will send a request, a “Received a request” message will be shown on the console screen.

response.writeHead(200, {“Content-Type”: “text/html”});

After that, I’ve used the response.writeHead() method that sends a response header back to the user with the HTTP status code 200 and “text/html” MIME type of the response.

response.write(“Hello Everyone”);

response.end();

And then, I’ve added a message “Hello Everyone” that will be displayed on the HTML page. Later, I’ve called the response.end() method to instruct the server to end the output stream.

server.listen(8080);

console.log(“Server is listening”);

Finally, I’ve set the server to listen on port 8080 for incoming connections and show a message “Server is listening” on the console screen.

 

An Example of Simple File I/O with Node.js

Because Node.js has an extremely useful and powerful set of libraries, the possibilities of what you can do are endless. In the following example, I’ll show you how to open a log file and parse it. So I’ve created a file named “log”, filled it with the text given blow and saved it with .text extension.

log.txt:

2014-11-17T13:50:33.166Z A 5

2014-11-17T13:51:33.166Z B 3

2014-11-17T13:52:33.166Z C 8

2014-11-17T13:53:33.166Z B 2

2014-11-17T13:54:33.166Z B 1

As you can see, each message in this log data contains a date, a letter, and a value. What I want to do is to add up the values for each letter. So I’ve created a JavaScript file named “parser.js” with the following code.

parser.js:

var fs = require(‘fs’);

fs.readFile(‘log.txt’, function (err, logData) {

                        if (err) throw err;

                        var text = logData.toString();

});

Let me explain what’s going on in the above code. The fs is the built-in file system module that has a function named readFile. This function takes the path of file and a callback. As the file data comes in the form of a byte array, I’ve used the toString() function for converting it to a string. Let’s add some more JavaScript to above code:

parser.js:

var fs = require(‘fs’);

fs.readFile(‘log.txt’, function (err, logData) {

                 if (err) throw err;

                 var text = logData.toString();

var results = {};

                 var lines = text.split(‘\n’);

                 lines.forEach(function(line) {

                        var parts = line.split(‘ ‘);

                        var letter = parts[1];

                        var count = parseInt(parts[2]);

                        if(!results[letter]) {

                                    results[letter] = 0;

                                    }

                        results[letter] += parseInt(count);

                        });

                 console.log(results);

});

Now, it’s time to print the result by passing parser.js file as a parameter to the node command.

node parser.js

You’ll see a massage showing sum of values for each letter, like so:

{ A: 5, B: 6, C: 8 }

 

Author Bio:-
Ajeet is an experienced WordPress developer who is working with WordPressIntegration – Developing WP themes from PSD. In his spare time, he writes about different topics related to HTML5, Responsive, WordPress, eCommerce, and JavaScript to share his work experience with others. For weekly updates, follow @Wordpress_INT.


About the author

With a passion for Knowledge, Smashinghub has been created to explore things like Free Resources For Designers, Photographers, Web Developers and Inspiration.

Twitter Visit author website

Subscribe to Smashing Hub


Comments are closed.