Node JS

The main reason NodeJS exists is to allow us to run Javascript on a computer or a server. It lets us access the file system or databases …. and other things you can do with a traditional serverside language. You couldn’t do that with JS before.

NodeJS is very fast, huge ecosystem for JS, great for the realtime look and feel for web apps. 

V8 Engine

V8 is a JavaScript engine built at the google development center, in Germany. It is open source and written in C++. It is used for both client side (Google Chrome) and server side (node.js) JavaScript applications.

V8 was first designed to increase the performance of the JavaScript execution inside web browsers. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The main difference with V8 is that it doesn’t produce bytecode or any intermediate code.

The aim of this article is to show and to understand how V8 works, in order to produce optimized code for both client side or server side applications. If you are already asking yourself “Should I care about JavaScript performance?” then I will answer with a quote from Daniel Clifford (tech lead and manager of the V8 team): “It’s not just about making your current application run faster, it’s about enabling things that you have never been able to do in the past”.

Rest of this article >>

Javascript Engine for idiots >>

Google Develepor Pages >>

V8 project github >>

Googles V8 engine | available to use | look at | even change (open source).  It was built to be used in the Chrome browser but it was built in a way that it can be used in other ways also. One of the key features of V8 is adding features and capabilities to javascript. It can run stand alone OR it can be embedded into any C++ application because V8 is C++. NodeJS takes advantage of this last part. V8 makes it possible to make C++ code available to JS.

First Class Functions and Function Expressions

First Class Functions – Everything you can do with other types can also be done with functions. Most other programming languages do not have this but JS does. An Expression – A block of code that results in a value. Function expressions are possible in JS because functions are first class. First class also means that they can be passed around like variables. Functions in JS are a kind of object and that is why it is possible to pass it around.

The pattern employed a lot in Node JS is that functions are assigned to variables, the variable is then passed as an argument in another function which is then called.

Like this:

var daVar = function(){
console.log('Rockin in the free world .....');
}

Then you can make another function (which accepts an argument) like this:

function printStuff(stuff){
stuff();
}

Now you can caall the function printStuff and pass daVar as an argument. Like this:

printStuff(daVar);

Modules in Node JS

Module = reusable block of code whose existense does not accidentally impact other code. Javascript didnt get this until ES6. Lower versions of JS can achieve modules by using NodeJS.

Pretty simple really. Since a module is designed to be reusable, there really is no point making one for one time use. But if the module is used by multiple functional components OR if it makes sense from a testing and support perspective, then the capability can be modularised.

A module should be a seperate js file. To include it in your app file, there are really only 2 things you need to keep in mind:

  1. export it –> explicitally export the module and CHOSEN capabilities
    • module.exports = thingy (thingy is what will be returned)
    • Now this module is making the thingy available for use outside the module.
    • Remember, thingy may be a function. Thats why we set it to a variable (next part)
  2. require it
    • var myVariable = require(‘./sample’);
    • in the app.js file – the ./indicates that the file called sample.js is a custom file and lives in the same directory as the calling js file
    • To require nodes own modules, you do the same thing but leave out the ./
    • You can now use myVariable

It is worth remembering that myVariable could be anything. Could be a class, a single function (which may accept one or more arguments) or even simply a variable.

Magic!

Module Patterns

ES6 introduces a new concept to javascript called template strings. Basically what they bring to the table is the ability to plug values into what are essentially strings. The funtionality exists already in other languages (like php).

var num1 = 6;
var num2 = 4;
console.log(`the sum of $num1 and $num2 is ${num1+num2}`;

Note you need to use backticks, not quotation marks!

Ok, lets talk patterns. In the example above we exported a function like this

module.exports = function1;

But what if you have function2 in the module file as well (and a variably called key), how will that be used. Node JS allows us to add properties to the module.exports. Like this:

module.exports.func1 = function1;
module.exports.func2 = function2;
module.exports.key = key;

Now when we require our module and store the returned result in a variable, we should be able to access everything that is being exported. So if I require the module 

var stuff = require('./sample');

I can access the functions and variable like this:

stuff.func1();
stuff.func2();
stuff.key;

A quicker way to do the above is to, instead of specifically saying module.exports.blah for each module component, we could declare them for export from the beginning.

module.exports.func1 = function(){};
module.exports.key = someValue;
etc ...

One more way to do it is using object literal notation like this:

module.exports = {
func1: function1,
func2: function2,
key: key
}

This allows us to protect our object and only expose what we want to expose.

Event Emitter

Now we are talking about a Node JS core module so the require is a little easier. No ./ needed.

var events = require('events');

One of the things returned from this module is the Event Emitter. This is a constructor so I can create an event emitter like this

var myEmitter = new events.EventEmitter();

Lots of frameworks support events. Like in jQuery you can have 

Element.on('click', function(){
doSomething();
});

In JQuery, the events are predefined. Node JS is a bit similiar but it allows you to create your own events. This means you can Emit your own custom events and also Catch your own custom events.

Our custom Catch/on will look like this

myEmitter.on(‘someEvent’, function(message){
console.log(message);
});

Our custom emit will look like this

myEmitter.emit(‘someEvent’, ‘The event was emitted!’);

Thats all wonderful but it is only usefull if we can attach the functionality to another object. We want to be able to create objects and then emit and catch events from that object. How to do that?

In Node JS you need to import another standard module
var events = require('events');
var util = require('util);

Create an object for demo purposes

var Person = function(name){
this.name = name;
};

To be able to emit and catch events from person oblects, we need to do this

util.inherit(Person, events.EventEmitter);

Now anything created on the back of the Person constructer wi
ll be able to have custome events attached to it. 

The above is very high level and doesnt really explain how this works. Further explanation can be found here.

The File system

Web Server - routing

Web Server - Express

Web Server - Templating