Get programming with node js 

What is Node.js? There is a lot of confusion among beginners because they don’t understand what Node.js is. And even the description from the official site is no help. The important thing to realize is that Node is not a Web server. The platform itself does not do anything. It doesn’t work like Apache. There…

What is Node.js?

There is a lot of confusion among beginners because they don’t understand what Node.js is. And even the description from the official site is no help.

The important thing to realize is that Node is not a Web server. The platform itself does not do anything. It doesn’t work like Apache. There are no configuration files in which it points you to HTML files. If you want the platform to be an HTTP server, you’ll have to write an HTTP server (using built-in libraries).

Node.js is just another way to run code on your computer. It’s an execution environment for the JavaScript language.

Installing Node

Node.js is easy to install. All you have to do is go to the download page of the official site.

I installed it, and now what?
After installing, you have a new command at the command line, “node.” You can use node in two ways.

The first is without arguments: this command will open an interactive mode at the command line where you can execute the JavaScript code.$ node > console.log(‘Hello World’); Hello World undefined

In this example, I simply typed “console.log(‘Hello World’);” and pressed Enter. The Node will start executing and we will see our message. It will also write “undefined” because it prints the return value, and console.log returns nothing. – Another way to use Node.js is to create a Javascript file.

So, we create a file:


console.log('Hello World');

And save it in the directory from which we will run this file. To go to just write in the command line cd full_directory_name

Run at the command line:

$ node hello.js
Hello World

In this case, we moved the message of the console.log file and sent that file to the node command as an argument. Node runs the JavaScript code in the file and prints out “Hello World”.

I/O files with node.js

Running pure JavaScript is great, but not very useful. That’s why Node.js has a huge number of libraries (modules) to do the real thing. In this example, we’ll open a log file and process it.


2013-08-09T13:50:33.166Z A 2
2013-08-09T13:51:33.166Z B 1
2013-08-09T13:52:33.166Z C 6
2013-08-09T13:53:33.166Z B 8
2013-08-09T13:54:33.166Z B 5

What this file means is not so important, but we need to know that each entry contains a date, a letter, and a value. We want to relate each letter to its corresponding value.

We need to read the contents of the file.


// Loading the file system module
var fs = require('fs');

// Read the contents of the file into memory
fs.readFile('example_log.txt', function (err, logData) {
	// If an error occurs, we throw an exception
	// and the program is terminated
	if (err) throw err;
	// logData is an object of type Buffer, translate into string
  		var text = logData.toString();

Fortunately, Node.js makes it very easy to handle the contents of a file using the built-in filesystem (fs) module. The fs module has a readFile function that takes the file path and a callback. The callback will be executed when the file is completely read. The file data comes in Buffer type form, which is a set of bits. We can convert it to a string using toString()

Now let’s add a parser (it’s written in pure JavaScript).


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);
// { A: 2, B: 14, C: 6 }

When the file is the argument of the node command, the result will be printed and the output will be executed.

$ node my_parser.js
{ A: 2, B: 14, C: 6 }

Asynchronous Calls in node.js

As you noted in the last example, node.js is characterized by the use of asynchronous calls. Essentially you’re writing what needs to be done, and when it’s done the callback will be triggered because node.js is single-threaded. While you’re waiting for the callback to run, node.js can go off and do other things instead of blocking until the request is complete.

This is especially important for web servers. It’s quite common for modern web applications to have access to databases. While you’re waiting for the database to return results, Node can handle more requests. This allows you to handle thousands of concurrent requests with little overhead compared to creating a separate thread for each connection.

Creating a web server with node.js

As mentioned before, Node can’t do anything on its own. One of the built-in modules makes it easy to create a simple HTTP server, an example of its use can be found on the homepage of the official site.


var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
console.log('Server running on port 8080.');

Once again, this is a basic web server, not a full-featured server. It cannot handle pictures or HTML files. In fact, whatever request you send, it will return “Hello World”. However, you can run this script, go to http://localhost:8080 in your browser, and see this text.

$ node mywebserver.js

You may have already noticed that your node.js application no longer stops. That’s because you’ve built a web server and your node.js app responds to requests until you stop it.

If you want to make a web server with full functionality, you’ll have to do some work: you’ll have to check all the requests, read the appropriate files, and send the output back. There is some good news. People have already done this hard work for you.

Express module for node.js

Express is a framework that will make it easy to create most common websites. First you will need to install it. Along with the node command, you will have access to the “npm” command. This tool gives you access to a huge number of modules created by the community, including Express.

$ cd /my/app/location
$ npm install express

When you install the module, it will be put in the node_modules folder in your application directory. Now you will be able to use its functionality as if it were built in.

Let’s create a basic static server using Express.


var express = require('express'),
    app = express();
app.use(express.static(__dirname + '/public'));

Run the script:

$ node mystaticfile_server.js

Now you have a pretty capable static file server. Anything you put in the public folder can be queried and displayed by a browser: HTML, pictures, almost anything. So, for example, if you put a picture called “my_image.png” inside the public folder, you can open the picture directly in the browser by going to http://localhost:8080/my_image.png. Of course, Express has pretty extensive functionality and you can explore it during development.


We touched a little bit on NPM in the previous section, but we want to stress how important this tool is for normal Node.js development. Thousands of modules are available to solve almost every typical problem you are likely to encounter. Remember, it’s worth checking out NPM before you reinvent the wheel. It is typical for a typical node.js application to have a lot of plugins.

In the previous example we manually installed Express. If you have a lot of connected libraries, it’s not a good idea to install them all. That’s why npm uses the package.json file.


  "name" : "MyStaticServer",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "3.3.x"

The package.json file contains an overview of your application. There are many fields available here, but the necessary minimum is presented. The “dependency” section describes the name and version of the modules you would like to install. In this case we accept any version of Express.3.3. In this section you can list as many libraries as you like.

Now, instead of installing each library separately, we can run one command and install everything we need in one fell swoop.

$ npm install

When you run the command, npm will search the current folder for the package.json file. If it finds it, it will install every library on the list.

Organizing the code in node.js

So far we’ve been using a single file, but it’s very hard to maintain a project that way. In most applications your code will be in several files. There’s no standard or forced organization of which files go where. This is not Rails. You do what you want to do.

Let’s reorganize the script that handles the record file. Subsequently it will be much easier to test and maintain if we put the parsing logic in a separate file.


// Handler constructor
var Parser = function() {
// Processes the specified text
Parser.prototype.parse = function(text) {
var results = {};
// Turns text into an array of lines
var lines = text.split('\n');
lines.forEach(function(line) {
    var parts = line.split(' ');

What we did was to create a new file containing the logic to handle the entries. This is just standard JavaScript code, and there are many ways to implement this code. We chose how to define the new JavaScript object, and it’s easy to module test it.

The important line is “module.exports.” This is an explanation for Node what you are exporting from this file. In this case, I’m exporting a constructor, so users can create instances of my Parser type object. You can export whatever you want.

// Require my new parser.js file.
var Parser = require('./parser');
// Load the fs (filesystem) module.
var fs = require('fs');
// Read the contents of the file into memory.
fs.readFile('example_log.txt', function (err, logData) {
// If an error occurred, throwing it will
  // display the exception and kill our app.
  if (err) throw err;
// logData is a Buffer, convert to string.
  var text = logData.toString();
// Create an instance of the Parser object.
  var parser = new Parser();
// Call the parse function.
  // { A: 2, B: 14, C: 6 }

Files are included just like modules, with one difference: you provide the path to the file instead of the name. The .js extension implies that you can leave the habit of writing the extension at the end if you like.

Since we exported a constructor, this is what will be returned from the request. Now we can create instances of objects like Parser and use them.


Hopefully this tutorial has been a bridge between installing Node.js and your first application. Node.js is a very powerful and flexible technology with which you can solve a wide range of problems.

We want to remind you that using Node.js is limited only by your imagination. The kernel libraries are very neatly designed and provide any tools you need to build your application. By combining all the modules available in npm, you may be surprised how quickly you can build extremely difficult and just as interesting applications.

Similar Posts

Leave a Reply

Your email address will not be published.