• 15 heures
  • Difficile

Mis à jour le 17/12/2019

Node.js: what is it for exactly?

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

Let’s start by answering all the questions that are running through your mind:

  • Why do web developers seem to like Node.js so much?

  • Why is it based on JavaScript? I thought this language was only used to add effects on a webpage?

  • Where does the presumed speed of Node.js come from? How can it help me?

  • Is this thing reliable? Who uses it (other than bearded geeks!)? Should I use it too?

In this first chapter, I’m going to answer all your questions, plus some you haven’t thought of yet. :)

Then, if you’re feeling brave, we will take the next step and install Node.js on your device!

From "old school" JavaScript to Node.js

OK, so the expression "old school JavaScript" may be a bit of an exaggeration,
but there is some truth in it and JavaScript has been through several incarnations. It used to have a bad reputation. For a long time, it was seen as "a little something that would occasionally come in handy to add effects to a webpage". However, JavaScript is primarily a language just as much as C, Ruby, PHP, and many others are.

Now, JavaScript is getting its own back.
Developers are realizing that this language, that they have ignored and sometimes even despised for so long, has actually been playing its cards close to its chest.

JavaScript isn’t just a small utilitarian language.
It’s totally different to Java, C, and many other languages.
It can be difficult to use, but it is very powerful.

JavaScript was created in 1995 (in the prehistoric era of computing, can you believe it?), and it has evolved a great deal since then. I said earlier that JavaScript had been through several incarnations as a programming language. To be more specific, I would say that it has had 3 lives (see next figure):

  1. In the 90s, people used DHTML (Dynamic HTML). The first JavaScript versions were used to add small effects to a webpage, such as displaying an image when a button was clicked. It was the era of Netscape and Internet Explorer 5.5.

  2. In the first decade of the new millennium, we started to use JavaScript to create client-side interfaces. This is when libraries such as jQuery or Mootools appeared. Today, this use of JavaScript is very widespread and accepted. We have gotten used to manipulating the DOM (Document Object Model) to pass HTML tags through JavaScript and submit to all sorts of processes.

  3. Then, around 2010, JavaScript entered a new era. Google started to make the language much faster by launching their Google Chrome browser. This new browser gave birth to the V8 engine, which greatly increased the running speed of JavaScript code (I’ll come back to that). Tools like Node.js followed, as well as many libraries with a .js extension: Backbone.js, Ember.js, Meteor.js. So now JavaScript sounds cool again and also seems more sophisticated than it did at first.

The 3 lives of JavaScript
The 3 lives of JavaScript

Let’s be clear: jQuery isn’t dead and it doesn’t mean that it shouldn’t be used anymore (however, DHTML and Netscape are well and truly dead). The new JavaScript tools such as Node.js do things differently to jQuery and the likes. The two can complement each other.

But what can we actually do with Node.js?

Node.js lets us use JavaScript language on the server… so it allows us to write JavaScript outside the browser!
Node.js has all the power of JavaScript and offers us a whole new way of developing dynamic websites.

Now let’s see in more detail how Node.js works. :)

Node.js: server-side JavaScript

Until now, JavaScript has always been used on the client’s side, i.e. the side seen by visitors browsing our websites. The visitor’s browser (Firefox, Chrome, IE, etc.) runs the JavaScript code and performs the actions on the webpage (see next figure).

Classic diagram: PHP on the server, JavaScript for the client
Classic diagram: PHP on the server, JavaScript for the client

What changes with the arrival of Node.js?

We can still use JavaScript on the client-side to manipulate the HTML page. No change there.

However, Node.js offers a server-side environment, which allows us to also use JavaScript language to generate web pages. Basically, it replaces server languages such as PHP, Java EE, etc. (see next figure).

With Node.js, we can also use JavaScript on the server!
With Node.js, we can also use JavaScript on the server!

Why does Node.js seem different? Is it because it uses JavaScript?

Yes, it’s because JavaScript is a language based on events, therefore Node.js is in itself based on events. So, it’s the entire way of writing applications that has changed. This is where Node.js draws all its power and speed from.

With Node.js, you can create fast applications such as:

  • A chat server;

  • A very fast upload system;

  • And generally speaking, any application that needs to respond to numerous requests rapidly and efficiently, in real time.

JavaScript is not really an Object Orientated language;, so it’s a long way from Java, Ruby, and Python. Writing an application with Node.js requires an entirely different mind-set! This is slightly disconcerting to begin with, to be honest with you, but once you start to get the hang of this tool, you’ll feel like you just acquired a new superpower out of the blue.
This is why so many bearded geeks are excited about Node.js! (see next figure)

I used to be a bearded guy...
I used to be a bearded guy...

Why is Node.js fast?

The speed of Node.js is mainly down to two things: the V8 engine and its non-blocking feature.

The V8 engine

Node.js uses Google Chrome’s ultra fast V8 execution engine. This V8 engine created a lot of noise when Google Chrome was first released, because it’s an Open Source tool created by Google which analyses and runs JavaScript code very quickly (see next figure).

The logo of Google’s JavaScript V8
The logo of Google’s JavaScript V8

Until the release of Chrome, most browsers read JavaScript inefficiently: the code was read and interpreted bit by bit. The browser took a lot of time to read JavaScript and to convert it to machine language so it could be understood by the processor.

Google Chrome’s V8 engine, which has been reused here by Node.js, works completely differently. It is highly optimized and carries out what we call JIT (Just In Time) compilation. It quickly transforms JavaScript code into machine language and even optimizes via complex processes like code inlining and copy elision, amongst others.

You don’t need to know how V8 works to be able to use Node.js. Just remember that it allows the running of JavaScript to be ultra fast (and that its creators, Google’s developers, are genuine beardy guys :-° ).

Non-blocking model

As JavaScript is a language built around the idea of events, Node.js allows an entirely non-blocking code algorithm to be put into place.

By the way, do you know the difference between a blocking code and a non-blocking code? Hmmm, perhaps a little explanation is called for! ;)

Blocking model vs. non-blocking model

Imagine a program which is created to upload a file and then display it. This is how we would write the code in a blocking model:

Upload the file
Display the file
Do something else

The actions are carried out in order. The lines need to be read from top to bottom:

  1. The program will upload a file to the Internet.

  2. The program will display the file to the user.

  3. Then, the program can do other things (i.e. carry out other actions).

Now, we can write the same code in a non-blocking model:

Upload a file
As soon as it’s finished, display the file
Do something else

The program no longer carries out the tasks in the order that they are written. It does this:

  1. The program launches the upload of the file to the internet.

  2. The program does other things (the program follows its course).

  3. As soon as the upload is finished, the program carries out the actions that we asked it to do: it displays the file.

Schematically, the running of the program can therefore be represented as in the next figure.

The non-blocking model in programming
The non-blocking model in programming

This is exactly how Node.js works. As soon as "File uploaded" appears, a function known as a callback function is called and carries out actions (here, the callback function displays the file).

The non-blocking model with Node.js

What does it look like with real code? Here’s an example of Node.js programming which uploads a file to the internet and displays "File uploaded!" when it’s finished:

request(‘http://www.site.com/file.zip', function (error,
response , body) {
console.log("File uploaded!");
console.log("I do other things while I’m waiting…");

The upload request is launched first. Then, the program does other things (here, it displays a message in the console, but it could do anything). As soon as the upload has finished, the program goes to line 2 and displays "File uploaded!".

But how does it work? I can see a function in the settings of the function request. It’s a function within a function, these beardy guys are crazy - help!

Don’t panic! What you can see here is a callback function. In JavaScript, we can happily send a function as a setting for another function. In this case it means "Run this function when the upload is finished".

Here, the function doesn’t have a name, so we call it an anonymous function. But we could separate the code like this, the result would be identical:

// Identical result to the previous code
var callback = function (error, response, body) {
console.log ("File uploaded!");
request (‘http://www.site.com/file.zip',callback);
console.log ("I do other things while I’m waiting… ");

The callback function is saved in a variable. As with all functions, it is not run if hasn’t been called.
Then, we send this callback function as a setting of the request () saying: "As soon as the upload request has finished, call this callback function".

Practically speaking, JavaScript developers often put anonymous functions directly within other functions in settings, like in my first code. It’s a bit strange to start with, but you soon get used to it!

I don’t see why it would make the program run faster. It looks as if it’s making it more complicated, if anything!

I told you that Node.js wasn’t simple, but it’s worth it! You’ll see why. Imagine that we ask for 2 files to be uploaded using Node.js:

var callback = function (error, response, body) {
console.log ("File uploaded!");
request (‘http://www.site.com/file.zip’, callback);
request (‘http://www.site.com/otherfile.zip’, callback);

If the model had been blocking, the program would have:

  1. Launched the upload of file 1 and waited for it to finish.

  2. Then launched the upload of file 2 and waited for it to finish.

However, with Node.js, the two uploads are launched at the same time. The program doesn’t wait for the end of the first upload to go to the following instruction.

Therefore, the upload of both files goes a lot quicker because the program does them both at the same time (see next figure):

In a non-blocking model (like Node.js), the 2 files are uploaded at the same time and the whole thing finishes quicker
In a non-blocking model (like Node.js), the 2 files are uploaded at the same time and the whole thing finishes quicker

It’s common in web applications to have long blocking operations such as:

  • Calls to databases

  • Calls to web services (ex: Twitter’s API)

Node.js stops us wasting all that time by letting us do other things while we wait for long actions to finish!

Summing up

  • Node.js is a development environment, which allows for server-side coding in JavaScript. In this sense, it can be compared to PHP, Python/Django, Ruby on rails, etc.

  • Writing an application using Node.js requires a particular frame of mind because everything is based on events.

  • Node.js is recognized and appreciated for its speed: a Node.js program never hangs around doing nothing! 

Exemple de certificat de réussite
Exemple de certificat de réussite