Node.js – Get started

Maria Cristina Di Termine
20-07-2016

This is a little tutorial for those who want to learn Node.js but don’t know where to start with it.

What is Node.js?

It seems that there is confusion about what actually Node.js is. In the official website we can find a definition of it but… eh? Simply saying, Node.js is an open-source, cross-platform, JavaScript runtime based library, another way to execute code on our computers. Node.js allows the creation of Web servers (it is not a webserver itself).

Get started

First thing to do is installing Node.js in your machine. For Windows or Mac users the inhalers are available here. When we get it installed we can already run it in our console using the command called “node”. The node command can be used in 2 different ways: using REPL or providing a file to execute (most used). REPL (read-eval-print-loop) is an interactive shell that node opens and where you can run plain JavaScript code. For example we could type in our console something like this:

$ node
$ console.log('Hello World');

Node will run the code and this will be what we will get:

Hello World
undefined

“Hello World” is what we get printed from the console.log method but Node will return the value of every command inside the REPL and since “console.log” doesn’t return a value, that’s why we get also “undefined”.
The most used why is instead providing Node a file to run. If we create a file with a simple JavaScript code inside we can easily run it. Create a file with this simple line of code:

console.log('Hello World');

In your console type this:

$ node file.js

This is what you will get:

$ node file.j

Hello World

What we actually did is sending the file.js to the node command as an argument so that Node can run it and print out the console.log method.

That was the base to get started Node.js but now let’s do something “real”. Node can run plain JavaScript easily but it’s not all. Indeed Node provides several modules to do more complex and useful things.

Let’s create for example a simple log file with some information in it:

file_log.txt
Mary A 2
Michael B 1
Finn C 6
Sarah B 8
Erik B 5

In this file we have 5 lines which contain each a name, a letter and a value. What we want to do is read the file and parsing the information.

First, create the js file that Node will run and insert this code:

// Load the fs (filesystem) module
var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('file_log.txt', function (err, logData) {

  // If an error occurred, throwing it will
  // display the exception and end our app.
  if (err) throw err;
  
// logData is a Buffer, convert to string.
  var text = logData.toString();
});

As you see we used the Node method filesystem (fs) which has a function called readFile that uses a file path and a callback as arguments. The file data will be loaded in the form of a Buffer (a byte array) so we need to convert it to a string using the method toString(). Now we can parse it:

// Load the fs (filesystem) module.
var fs = require('fs');// 

// Read the contents of the file into memory.
fs.readFile('file_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();
  
var results = {};

// Break up the file into lines.
  var lines = text.split('\n');
  
lines.forEach(function(line) { //Go through every line
    var parts = line.split(' '); //Divide the string by space ''
    var letter = parts[1]; //Take second idem of the array
    var count = parseInt(parts[2]); //Take third idem of the array
    
if(!results[letter]) {
      results[letter] = 0;
    }
    
results[letter] += parseInt(count);
  });
  
console.log(results);
  // { A: 2, B: 14, C: 6 }
});

Now if we run this file as argument to the node command it will print out the result:

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

Basically what we did is to use an asynchronous callback which is the typical pattern in Node.js.
We tell Node to do something and when it’s done it will run the callback (function). Node is indeed single-threaded and so it can do other things while we are waiting for the callback. This is very important for web servers: while we are waiting to get the database Node can execute more requests without getting stuck.
We can also create a simple HTTP server using the method createServer(). Here an example:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('My server is cool!!!\n');
}).listen(8080);

This is not a full featured http server of course, it can’t serve images or html. If you run now node my_web_server.js
and go to http://localhost:8080 you will see the text that the code return (‘My server is cool!!!’). Now if you want a full featured http server what you need is just an already existing framework of Node called Express. What it does at this point is see what is requested, read the files and send their content back to the server.
First thing to do is installing it:

npm install express

Second thing is writing this code:

var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/myFolder'));

app.listen(8080);

So now anything you put in the folder myFolder can be visible by the browser. If you put an HTML file into myFolder and go to http://localhost:8080/my_html_file.html you will get that html file. This is just the base that Express can do, I suggest to read more about it and Node.js. I hope this little tutorial was clear enough as introduction to Node. Of course this is just a minimal part of his power which is actually very large and varied maybe as a creative developer mind 🙂
Enjoy!

LEAVE A REPLY

you might also like