pello.info News http://www.pello.info/index.php/rss2 pello.info News syndication 2015-09-05 12:09:53 http://www.pello.info/index.php/rss2 es Rediscovering Javascript Objects http://www.pello.info/index.php/blog/rediscovering-javascript-objects http://www.pello.info/index.php/blog/rediscovering-javascript-objects 2015-04-08 00:05:38 pelloxabier http://www.pello.info/index.php/blog/rediscovering-javascript-objects

In this post I will introduce Javascript objects, how to define them, how to add attributes and methods and how to access them. Maybe you have heard that Javascript is an object oriented language but that definition is not very precise, specially when comparing to other languages. There are no classes! (and it is considered a prototypal object oriented language). Anyway now we will dip our toes into the waters just a little to become familiar with the notation. Prototypes, inheritance and other advance stuff will come next.

Creating an object

Did you read well? We are creating an object, not a class. Hey, this looks like a JSON String. You know what? JSON stands for JavaScript Object Notation, it has nothing to do with the argonauts or that amiable chap of Camp Crystal Lake. Basically you put key-value pairs inside curly brackets, where values can be any kind of js data: number, boolean, string, arrays, functions or even objects

// One single object
var oneUser = {
  login : 'falken',
  password : 'josua'
};

typeof oneUser;

otherUser = oneUser;

otherUser.login = 'root';
// Other way to access property
oneUser['password'] = '1234';

// The reference to the same!
console.log('One: ')
console.log(oneUser);
console.log('Other: ');
console.log(otherUser);

Object { login="root",  password="1234"}
Object { login="root",  password="1234"}

As you can see both oneUser and otherUser variables hold a reference to the same object.

Keys with quotes or not

We can leave out quotes, unless we want to use a key with special charactes, blank spaces, etc.. In the next example we can see how to reach attributes in two different ways and how to deal with nested objects.

var oneCustomer = {
  name : 'John Doe',
  'Customer address' : 'c/ unknown',
  '-+-+-+' : 'wtf',
  payment : { ptype : 'Visa',
             card  : '33442324234',
             'expiry date' : 'never'
            }
};

console.log(oneCustomer);

oneCustomer['name'] = '';
oneCustomer['-+-+-+'] = 'Something';
oneCustomer.payment['ptype'] = 'Account';
oneCustomer['payment'].card = '666';
oneCustomer['payment']['expiry date'] = 0;

console.log(oneCustomer);

Functions as data

Ok, if we want these objects to behave as objects in other languages, we should add some code to them. Easy peasy.

var student = {
  id : 2,
  name : 'John Doe',
  sayHello : function () {
              return 'Hello';
            }
}

console.log(student);
console.log(student.sayHello());

Hello

By now maybe you have realized that Javascript hashtables are in fact objects

Adding more properties and methods

Why not? Javascript is interpreted and weakly typed. But don't get confused. We are still playing with objects, not with classes. When we want to extend attributes of functions to a class we can use prototype (not covered yet).

...
// Adding new properties and methods:
student.age = 28;
student.sayGoodbye = function () { return 'bye';};

console.log(student.sayGoodbye());
bye

this

The well-known this is available too in Javascript. It refers current object. It comes in handy when we need to refer to our own properties in the object functions.

This operator referes to current object

var invoice = {
  description : 'Sample invoice',
    price:100.0,
    vat: 5.0,
  subtotal : function () {
              return this.price;
            },
  total : function () {
              return this.price + ((this.price * this.vat)/100);
            }
}

console.log(invoice);
console.log(invoice.total());

Constructors

Ok, we have been playing around with single instances, but what if we want to create different instances of the same kind of object. There is no class keyword, but we can define a constructor function and the call it using new reserved word to create a fresh new instance.

The next example shows a class of a kind in Javascript. It is a function with the name starting with uppercase (a convention to make it clear that this is not an ordinary function but a constructor), and inside we just add attributes and functions.

/**
* constructor for Web objects
*/
function Web () {
  this.url = 'http://localhost';
  this.name = 'Localhost';
  this.showInfo = function () {
    return this.url + ': ' + this.name;
    }
}

var oneWeb = new Web();
oneWeb.url = 'http://www.pello.info';
oneWeb.name = 'Home sweet home';

console.log(oneWeb);
console.log(oneWeb.showInfo());

var otherWeb = new Web();
otherWeb.url = 'http://www.elmundo.es';
otherWeb.name = 'El Mundo';

console.log(otherWeb);
console.log(otherWeb.showInfo());

Calling this function with new will create different instances.

Constructor with arguments

Being a function, adding arguments to the constructor is pretty straightforward.

/**
* constructor for Web objects
*/
function Web (url, name) {
  this.url = url;
  this.name = name;
  this.showInfo = function () {
    return this.url + ': ' + this.name;
    }
}

var oneWeb = new Web('http://www.pello.info','Home sweet home');

console.log(oneWeb);
console.log(oneWeb.showInfo());

var otherWeb = new Web('http://www.elmundo.es','El Mundo');

console.log(otherWeb);
console.log(otherWeb.showInfo());

constructor property and instanceof operator

Every object has at least a constructor property that we can check. Also, we can check if an object is an instance of certain type. I'm reluctant to say class.

typeof oneWeb;
"object"

oneWeb.constructor;
Web(url, name)

// Instance of operator
if (oneWeb instanceof Web) {
    console.log('Instance of Web');
}

Factory

Do you prefer factories to create instances? just create a function that returns an object.

function factory (title,text) {
  return {
    title : title,
    text : text,
    show: function () {
              return title + ': ' + text;
           }
  };
}

var comment = factory('sample','bla bla');
var comment2 = factory('sample2','bla2 bla2');
var comment3 = factory('sample2','bla2 bla2');

comment.title = 'Other';
console.log(comment);
console.log(comment.show());

console.log(comment2);
console.log(comment2.show());

Equality

Are two object equals? Not at all, the equality refers to be the same reference, that is, to point to the same object.

// Both of these are not equals
if (comment2 == comment3) {
    console.log('Are equals ==');
} else {
    console.log('Are not equals ==');
}
Are not equals ==

if (comment2 === comment3) {
    console.log('Are equals ===');
} else {
    console.log('Are not equals ===');
}
Are not equals ===

Now by reference turns out to be... true

var comment4 = comment3;

if (comment3 == comment4) {
    console.log('Are equals ==');
} else {
    console.log('Are not equals ==');
}
Are equals ==
if (comment3 === comment4) {
    console.log('Are equals ===');
} else {
    console.log('Are not equals ===');
}
Are equals ===

That's all for today. Object oriented Javascript is a hard road at first, but the payoff is worth it. Or so they say, greetz ;)

]]>

In this post I will introduce Javascript objects, how to define them, how to add attributes and methods and how to access them. Maybe you have heard that Javascript is an object oriented language but that definition is not very precise, specially when comparing to other languages. There are no classes! (and it is considered a prototypal object oriented language). Anyway now we will dip our toes into the waters just a little to become familiar with the notation. Prototypes, inheritance and other advance stuff will come next.

Creating an object

Did you read well? We are creating an object, not a class. Hey, this looks like a JSON String. You know what? JSON stands for JavaScript Object Notation, it has nothing to do with the argonauts or that amiable chap of Camp Crystal Lake. Basically you put key-value pairs inside curly brackets, where values can be any kind of js data: number, boolean, string, arrays, functions or even objects

// One single object
var oneUser = {
  login : 'falken',
  password : 'josua'
};

typeof oneUser;

otherUser = oneUser;

otherUser.login = 'root';
// Other way to access property
oneUser['password'] = '1234';

// The reference to the same!
console.log('One: ')
console.log(oneUser);
console.log('Other: ');
console.log(otherUser);

Object { login="root",  password="1234"}
Object { login="root",  password="1234"}

As you can see both oneUser and otherUser variables hold a reference to the same object.

Keys with quotes or not

We can leave out quotes, unless we want to use a key with special charactes, blank spaces, etc.. In the next example we can see how to reach attributes in two different ways and how to deal with nested objects.

var oneCustomer = {
  name : 'John Doe',
  'Customer address' : 'c/ unknown',
  '-+-+-+' : 'wtf',
  payment : { ptype : 'Visa',
             card  : '33442324234',
             'expiry date' : 'never'
            }
};

console.log(oneCustomer);

oneCustomer['name'] = '';
oneCustomer['-+-+-+'] = 'Something';
oneCustomer.payment['ptype'] = 'Account';
oneCustomer['payment'].card = '666';
oneCustomer['payment']['expiry date'] = 0;

console.log(oneCustomer);

Functions as data

Ok, if we want these objects to behave as objects in other languages, we should add some code to them. Easy peasy.

var student = {
  id : 2,
  name : 'John Doe',
  sayHello : function () {
              return 'Hello';
            }
}

console.log(student);
console.log(student.sayHello());

Hello

By now maybe you have realized that Javascript hashtables are in fact objects

Adding more properties and methods

Why not? Javascript is interpreted and weakly typed. But don't get confused. We are still playing with objects, not with classes. When we want to extend attributes of functions to a class we can use prototype (not covered yet).

...
// Adding new properties and methods:
student.age = 28;
student.sayGoodbye = function () { return 'bye';};

console.log(student.sayGoodbye());
bye

this

The well-known this is available too in Javascript. It refers current object. It comes in handy when we need to refer to our own properties in the object functions.

This operator referes to current object

var invoice = {
  description : 'Sample invoice',
    price:100.0,
    vat: 5.0,
  subtotal : function () {
              return this.price;
            },
  total : function () {
              return this.price + ((this.price * this.vat)/100);
            }
}

console.log(invoice);
console.log(invoice.total());

Constructors

Ok, we have been playing around with single instances, but what if we want to create different instances of the same kind of object. There is no class keyword, but we can define a constructor function and the call it using new reserved word to create a fresh new instance.

The next example shows a class of a kind in Javascript. It is a function with the name starting with uppercase (a convention to make it clear that this is not an ordinary function but a constructor), and inside we just add attributes and functions.

/**
* constructor for Web objects
*/
function Web () {
  this.url = 'http://localhost';
  this.name = 'Localhost';
  this.showInfo = function () {
    return this.url + ': ' + this.name;
    }
}

var oneWeb = new Web();
oneWeb.url = 'http://www.pello.info';
oneWeb.name = 'Home sweet home';

console.log(oneWeb);
console.log(oneWeb.showInfo());

var otherWeb = new Web();
otherWeb.url = 'http://www.elmundo.es';
otherWeb.name = 'El Mundo';

console.log(otherWeb);
console.log(otherWeb.showInfo());

Calling this function with new will create different instances.

Constructor with arguments

Being a function, adding arguments to the constructor is pretty straightforward.

/**
* constructor for Web objects
*/
function Web (url, name) {
  this.url = url;
  this.name = name;
  this.showInfo = function () {
    return this.url + ': ' + this.name;
    }
}

var oneWeb = new Web('http://www.pello.info','Home sweet home');

console.log(oneWeb);
console.log(oneWeb.showInfo());

var otherWeb = new Web('http://www.elmundo.es','El Mundo');

console.log(otherWeb);
console.log(otherWeb.showInfo());

constructor property and instanceof operator

Every object has at least a constructor property that we can check. Also, we can check if an object is an instance of certain type. I'm reluctant to say class.

typeof oneWeb;
"object"

oneWeb.constructor;
Web(url, name)

// Instance of operator
if (oneWeb instanceof Web) {
    console.log('Instance of Web');
}

Factory

Do you prefer factories to create instances? just create a function that returns an object.

function factory (title,text) {
  return {
    title : title,
    text : text,
    show: function () {
              return title + ': ' + text;
           }
  };
}

var comment = factory('sample','bla bla');
var comment2 = factory('sample2','bla2 bla2');
var comment3 = factory('sample2','bla2 bla2');

comment.title = 'Other';
console.log(comment);
console.log(comment.show());

console.log(comment2);
console.log(comment2.show());

Equality

Are two object equals? Not at all, the equality refers to be the same reference, that is, to point to the same object.

// Both of these are not equals
if (comment2 == comment3) {
    console.log('Are equals ==');
} else {
    console.log('Are not equals ==');
}
Are not equals ==

if (comment2 === comment3) {
    console.log('Are equals ===');
} else {
    console.log('Are not equals ===');
}
Are not equals ===

Now by reference turns out to be... true

var comment4 = comment3;

if (comment3 == comment4) {
    console.log('Are equals ==');
} else {
    console.log('Are not equals ==');
}
Are equals ==
if (comment3 === comment4) {
    console.log('Are equals ===');
} else {
    console.log('Are not equals ===');
}
Are equals ===

That's all for today. Object oriented Javascript is a hard road at first, but the payoff is worth it. Or so they say, greetz ;)

]]>
http://www.pello.info/index.php/blog/rediscovering-javascript-objects
Rediscovering Javascript functions http://www.pello.info/index.php/blog/rediscovering-javascript-functions http://www.pello.info/index.php/blog/rediscovering-javascript-functions 2015-04-06 00:28:43 pelloxabier http://www.pello.info/index.php/blog/rediscovering-javascript-functions

Javascript functions are apparently simple yet very flexible. Functions are data. Functions can be anonymous. Functions can even be shape shifters. And of course, closures deserve a look.

Simple function

This is a simple sample functions that generates a String, an excuse to introduce the most basic jsdoc notation.

/** 
 * Repeats a word
 * @author Pello Altadill
 * @param {string} word
 * @param {number} repeat
 * @returns {string} the word repeated 
 */
function printWord (word, times) {
    var printed = '';
    for (var i=0;i<times;i++) {
        printed = printed + word;
    }
    
    return printed;
}

printWord('a',5);
aaaaa

Beware global variables

Never forget this: if we define a variable without the var, it becomes a global, even if it is defined inside a function.

/**
* increments a global variable
* @author Pello Altadill
* @return {number} value of the global
*/
function increment () {
    if (typeof a == "undefined") {
       a = 0;
    } else {
        a++;
    }
    console.log('value is ' + a);
}

increment();

Global and local

This function plays with global and local variables. Results may not be surprising.


var everywhere = 6;
/**
* increments a global and local variable
* @author Pello Altadill
* @return {number} value of the global
*/
function increment () {
    var onlyLocal = 5;
    onlyLocal++;
    everywhere++;
    return onlyLocal;
}

console.log(increment());
console.log(everywhere);
console.log(increment());
console.log(everywhere);

6
7
6
8

Anonymous functions

These are javascript functions with no name at all. As you will see later on this post, they come in handy for certain purposes

/**
 * prints parameter to console
 * @author Pello Altadill
 * @param something to print
 * @return undefined
 */
function (something) { console.log(something); }

// Uses: 1. pass as parameter for callbacks
// 2. execute it right away

Functions are data

We can define a function, anonymous function with no name, and assign it to a variable. Then we can invoke our function through that variable.

/**
* adds two numbers
* @author Pello Altadill
* @param {string} a - first operand
* @param {number} b - second operand
* @return {number} - result of addition
*/
function add (a,b) { 
    return a+b;
}

var add = function(a,b) {return a+b;};
typeof add
"function"

add(40,2);
42

Callbacks

Callbacks are a key concept in javascript and fundamental in Node.js. The idea is simple, you pass a function as a parameter for other function and so calls are chained. In the next example we apply a callback function for array operations.

/**
* function with callback, to apply different operations to array values
* @author Pello Altadill
* @param {array} - numbers
* @param {function} - callback function 
* @return {array} - the resulting array
*/
function convert (numbers, convertCallback) {
    for (var i = 0;i>numbers.length;i++) {
        numbers[i] = convertCallback(numbers[i]);
    }    
    return numbers;
}



/**
* Multiplies a number with itself
* @param {number} - number in decimal base
* @return {number} 
*/
function power (number) {
    return number * number;
}

/**
* Decrements number
* @param {number} - number in decimal base
* @return {number} the
*/
function decrement (number) {
    return --number;
}


var someNumbers = [4,10,12,15,3];

convert(someNumbers,decrement);
[3,9,11,14,2]

convert(someNumbers,power);
[16,100,144,225,9]

Check documentation about javascript's forEach statement.

Self invoking functions

Apart from recursion, that is available indeed, in javascript we can create functions that after they are defined they are inmediately invoked. JUST ONCE though

/**
* self invoking function, executed only once
* @return {string}
*/
{
    function test () {
        console.log('I am executed only once.');
        return 'ok';
    }
}();

/**
* self invoking anonymous function, executed only once
* @param {string} name
* @param {string} version
* @return {string}
*/

{
    function  (name, version) {
        console.log('This is ' + name + ' program, v' + version);
    }
}('SelfInvoking','0.0.1');

Morphing functions

This may sound weird or somehow related to virus development, but in fact is one of the niceties of Javascript. The mechanism is easy as pie.

/**
* mighty morphing powerfunction 
* every time you invoke morphing it code changes..
* @author Pello Altadill
* @param {string} - name to be shown
*/
function morphing (name) {
    var person = name;
    console.log('Good morning ' + person);
    morphing = function () {
        console.log('Good afternoon ' + person);
        morphing = function () {
            console.log('Good night ' + person);
        }
    }
}
morphing('any');
"Good morning any"
morphing();
"Good afternoon any"
morphing();
"Good night any"
morphing();
"Good night any"
...

Variable scope chain

Functions can access global variables or variables defined in their parents. What happens when we have functions inside others? Just the same. There is a scope chain as you will see in this code.

/**
* simple function to try the scope chain inside functions
* NOTE: the scope is defined when functions are defined, not executed.
* @author Pello Altadill
* @param {number} - sample number
* @return {result}
*/
function scopeChain (someParam) {
    var top = someParam;
    console.log('Inside top level: ' + top );
    function chain1 () {
        var second = 42;
        console.log('Inside second level: ' + top + ", " +  second);
        function chain2 () {
            var third = 666;
            console.log('Inside third level: ' + top + ", " +  second + ", " + third);
        }        
        chain2();
    }
    chain1();
    if (typeof second == "undefined") {
        console.log('Cannot access variables inside other functions');
    }
}

scopeChain(15);

"Inside top level: 15"
"Inside second level: 15, 42"
"Inside third level: 15, 42, 666"
"Cannot access variables inside other functions"

Closures

classic closure explanation

Closures provide a mechanism to create private variables inside functions. They are based on the idea that you take out a function that resides in another function (the parent) but it is still linked to its parent function.

Example

To show how closures works, and different ways to create them, we will code around this example. It's a password generator that has two variables we would like to protect: totalLetters which indicates the length of the password and letters, which contains all the letters used to generate a password. The function uses an inner function; this approach will make it easy the transition to a closure where we will protect totalLetters and letters variables and we will make sure that they are initialized only once.

/**
* generates passwords
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
*/
function generatePassword () {
    var totalLetters = 8;
    var letters = 'abcdef23456789';
    console.log('Ok, initiliazed');
    function generate () {
        var result = '';
        for (var i = 0;i<totalLetters;i++) {
            result += letters[Math.round(Math.random()*(letters.length-1))];
        }        
        return result;
    }
    
    return generate();
}

generatePassword();
"fc498fa8"
"Ok, initiliazed"
generatePassword();
"55833ffd"
"Ok, initiliazed"
generatePassword();
"6b9edc75"
"Ok, initiliazed"

Closure, with a global variable

A simple solution, where we define a global variable and inside the function we assign the inner function to it.

// We define a global variable to hold the closure
var generate;

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
function generatePassword () {
    var totalLetters = 8;
    var letters = 'abcdef23456789';
    console.log('Ok, initiliazed only once.');
    generate = function () {
        var result = '';
        for (var i = 0;i<totalLetters;i++) {
            result += letters[Math.round(Math.random()*(letters.length-1))];
        }        
        return result;
    }
}

generatePassword();
"Ok, initiliazed only once."
generate();
"9ecb266b"
generate();
"58576336"
generate();
"7f87d274"

Closure, returning the inner function

If you don't like to mess around with a global variable inside your function, this is another way to create a closure

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
function generatePassword () {
    var totalLetters = 8;
    var letters = 'abcdef23456789';
    console.log('Ok, initiliazed only once.');
    var genFunction = function () {
        var result = '';
        for (var i = 0;i<totalLetters;i++) {
            result += letters[Math.round(Math.random()*(letters.length-1))];
        }        
        return result;
    }
    
    return genFunction;
}

var generate = generatePassword();

"Ok, initiliazed only once."
generate()
"23acce53"
generate()
"87aa77cc"
generate()
"78d653ec"

Closure, anonymous and selfinvoking

Putting it all together, this is how you create a closure like a sir.

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
var generatePassword = ( 
    function  () {
        var totalLetters = 8;
        var letters = 'abcdef23456789';
        console.log('Ok, initiliazed only once.');
        return function () {
            var result = '';
            for (var i = 0;i<totalLetters;i++) {
                result += letters[Math.round(Math.random()*(letters.length-1))];
            }        
            return result;
        }
    }
)();

"Ok, initiliazed only once."
generatePassword();
"3737c6c7"
generatePassword();
"ad5f5eb2"
generatePassword();
"cb684648"

Adding getters and setters

Why not? create some controlled access to your variables while keeping them private.

// We define the get/set references
var getTotalLetters, setTotalLetters;
var getLetters, setLetters;

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
var generatePassword = ( 
    function  () {
        var totalLetters = 8;
        var letters = 'abcdef23456789';
        console.log('Ok, initiliazed only once.');
        
        // We define get/set methods
        getTotalLetters = function () {
                        return totalLetters; 
                   };
        setTotalLetters = function (value) {
                        totalLetters = value;
                   };
        getLetters = function () {
                        return letters; 
                   };
        setLetters = function (value) {
                        letters = value;
                   };
                   
        return function () {
            var result = '';
            for (var i = 0;i<totalLetters;i++) {
                result += letters[Math.round(Math.random()*(letters.length-1))];
            }        
            return result;
        }
    
    }
)();

"Ok, initiliazed only once."
generatePassword()
"4c7d4b25"
generatePassword()
"88988ce6"
setTotalLetters(4)
generatePassword()
"ebb5"
generatePassword()
"cfcb"
getTotalLetters()
4
getLetters()
"abcdef23456789"
setLetters('xyz789')
generatePassword()
"7y77"
generatePassword()
"89yy"
generatePassword()
"zz7y"

Iterarion closures

This is a way to crea next(), hasMoreElements()-like iterators in Javascript.

/**
* closure to generate an iterator for arrays
* @author Pello Altadill
* @param {Array} array of elements
* @return {function}
* @greetz any
*/
function iterator(list) {
    var i = 0;
    return function(){
        return list[i++];
    };
}

var nextElement = iterator([15,42,666]);

while (var e = nextElement()) {
    console.log(e);
}

That's all for today. This is but a lame intro, anyway I hope that you find something useful. Mastering javascript functions is important if you want to move on and dive in Objects, prototype, and the like. Greets for you, as always ;)

]]>

Javascript functions are apparently simple yet very flexible. Functions are data. Functions can be anonymous. Functions can even be shape shifters. And of course, closures deserve a look.

Simple function

This is a simple sample functions that generates a String, an excuse to introduce the most basic jsdoc notation.

/** 
 * Repeats a word
 * @author Pello Altadill
 * @param {string} word
 * @param {number} repeat
 * @returns {string} the word repeated 
 */
function printWord (word, times) {
    var printed = '';
    for (var i=0;i<times;i++) {
        printed = printed + word;
    }
    
    return printed;
}

printWord('a',5);
aaaaa

Beware global variables

Never forget this: if we define a variable without the var, it becomes a global, even if it is defined inside a function.

/**
* increments a global variable
* @author Pello Altadill
* @return {number} value of the global
*/
function increment () {
    if (typeof a == "undefined") {
       a = 0;
    } else {
        a++;
    }
    console.log('value is ' + a);
}

increment();

Global and local

This function plays with global and local variables. Results may not be surprising.


var everywhere = 6;
/**
* increments a global and local variable
* @author Pello Altadill
* @return {number} value of the global
*/
function increment () {
    var onlyLocal = 5;
    onlyLocal++;
    everywhere++;
    return onlyLocal;
}

console.log(increment());
console.log(everywhere);
console.log(increment());
console.log(everywhere);

6
7
6
8

Anonymous functions

These are javascript functions with no name at all. As you will see later on this post, they come in handy for certain purposes

/**
 * prints parameter to console
 * @author Pello Altadill
 * @param something to print
 * @return undefined
 */
function (something) { console.log(something); }

// Uses: 1. pass as parameter for callbacks
// 2. execute it right away

Functions are data

We can define a function, anonymous function with no name, and assign it to a variable. Then we can invoke our function through that variable.

/**
* adds two numbers
* @author Pello Altadill
* @param {string} a - first operand
* @param {number} b - second operand
* @return {number} - result of addition
*/
function add (a,b) { 
    return a+b;
}

var add = function(a,b) {return a+b;};
typeof add
"function"

add(40,2);
42

Callbacks

Callbacks are a key concept in javascript and fundamental in Node.js. The idea is simple, you pass a function as a parameter for other function and so calls are chained. In the next example we apply a callback function for array operations.

/**
* function with callback, to apply different operations to array values
* @author Pello Altadill
* @param {array} - numbers
* @param {function} - callback function 
* @return {array} - the resulting array
*/
function convert (numbers, convertCallback) {
    for (var i = 0;i>numbers.length;i++) {
        numbers[i] = convertCallback(numbers[i]);
    }    
    return numbers;
}



/**
* Multiplies a number with itself
* @param {number} - number in decimal base
* @return {number} 
*/
function power (number) {
    return number * number;
}

/**
* Decrements number
* @param {number} - number in decimal base
* @return {number} the
*/
function decrement (number) {
    return --number;
}


var someNumbers = [4,10,12,15,3];

convert(someNumbers,decrement);
[3,9,11,14,2]

convert(someNumbers,power);
[16,100,144,225,9]

Check documentation about javascript's forEach statement.

Self invoking functions

Apart from recursion, that is available indeed, in javascript we can create functions that after they are defined they are inmediately invoked. JUST ONCE though

/**
* self invoking function, executed only once
* @return {string}
*/
{
    function test () {
        console.log('I am executed only once.');
        return 'ok';
    }
}();

/**
* self invoking anonymous function, executed only once
* @param {string} name
* @param {string} version
* @return {string}
*/

{
    function  (name, version) {
        console.log('This is ' + name + ' program, v' + version);
    }
}('SelfInvoking','0.0.1');

Morphing functions

This may sound weird or somehow related to virus development, but in fact is one of the niceties of Javascript. The mechanism is easy as pie.

/**
* mighty morphing powerfunction 
* every time you invoke morphing it code changes..
* @author Pello Altadill
* @param {string} - name to be shown
*/
function morphing (name) {
    var person = name;
    console.log('Good morning ' + person);
    morphing = function () {
        console.log('Good afternoon ' + person);
        morphing = function () {
            console.log('Good night ' + person);
        }
    }
}
morphing('any');
"Good morning any"
morphing();
"Good afternoon any"
morphing();
"Good night any"
morphing();
"Good night any"
...

Variable scope chain

Functions can access global variables or variables defined in their parents. What happens when we have functions inside others? Just the same. There is a scope chain as you will see in this code.

/**
* simple function to try the scope chain inside functions
* NOTE: the scope is defined when functions are defined, not executed.
* @author Pello Altadill
* @param {number} - sample number
* @return {result}
*/
function scopeChain (someParam) {
    var top = someParam;
    console.log('Inside top level: ' + top );
    function chain1 () {
        var second = 42;
        console.log('Inside second level: ' + top + ", " +  second);
        function chain2 () {
            var third = 666;
            console.log('Inside third level: ' + top + ", " +  second + ", " + third);
        }        
        chain2();
    }
    chain1();
    if (typeof second == "undefined") {
        console.log('Cannot access variables inside other functions');
    }
}

scopeChain(15);

"Inside top level: 15"
"Inside second level: 15, 42"
"Inside third level: 15, 42, 666"
"Cannot access variables inside other functions"

Closures

classic closure explanation

Closures provide a mechanism to create private variables inside functions. They are based on the idea that you take out a function that resides in another function (the parent) but it is still linked to its parent function.

Example

To show how closures works, and different ways to create them, we will code around this example. It's a password generator that has two variables we would like to protect: totalLetters which indicates the length of the password and letters, which contains all the letters used to generate a password. The function uses an inner function; this approach will make it easy the transition to a closure where we will protect totalLetters and letters variables and we will make sure that they are initialized only once.

/**
* generates passwords
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
*/
function generatePassword () {
    var totalLetters = 8;
    var letters = 'abcdef23456789';
    console.log('Ok, initiliazed');
    function generate () {
        var result = '';
        for (var i = 0;i<totalLetters;i++) {
            result += letters[Math.round(Math.random()*(letters.length-1))];
        }        
        return result;
    }
    
    return generate();
}

generatePassword();
"fc498fa8"
"Ok, initiliazed"
generatePassword();
"55833ffd"
"Ok, initiliazed"
generatePassword();
"6b9edc75"
"Ok, initiliazed"

Closure, with a global variable

A simple solution, where we define a global variable and inside the function we assign the inner function to it.

// We define a global variable to hold the closure
var generate;

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
function generatePassword () {
    var totalLetters = 8;
    var letters = 'abcdef23456789';
    console.log('Ok, initiliazed only once.');
    generate = function () {
        var result = '';
        for (var i = 0;i<totalLetters;i++) {
            result += letters[Math.round(Math.random()*(letters.length-1))];
        }        
        return result;
    }
}

generatePassword();
"Ok, initiliazed only once."
generate();
"9ecb266b"
generate();
"58576336"
generate();
"7f87d274"

Closure, returning the inner function

If you don't like to mess around with a global variable inside your function, this is another way to create a closure

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
function generatePassword () {
    var totalLetters = 8;
    var letters = 'abcdef23456789';
    console.log('Ok, initiliazed only once.');
    var genFunction = function () {
        var result = '';
        for (var i = 0;i<totalLetters;i++) {
            result += letters[Math.round(Math.random()*(letters.length-1))];
        }        
        return result;
    }
    
    return genFunction;
}

var generate = generatePassword();

"Ok, initiliazed only once."
generate()
"23acce53"
generate()
"87aa77cc"
generate()
"78d653ec"

Closure, anonymous and selfinvoking

Putting it all together, this is how you create a closure like a sir.

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
var generatePassword = ( 
    function  () {
        var totalLetters = 8;
        var letters = 'abcdef23456789';
        console.log('Ok, initiliazed only once.');
        return function () {
            var result = '';
            for (var i = 0;i<totalLetters;i++) {
                result += letters[Math.round(Math.random()*(letters.length-1))];
            }        
            return result;
        }
    }
)();

"Ok, initiliazed only once."
generatePassword();
"3737c6c7"
generatePassword();
"ad5f5eb2"
generatePassword();
"cb684648"

Adding getters and setters

Why not? create some controlled access to your variables while keeping them private.

// We define the get/set references
var getTotalLetters, setTotalLetters;
var getLetters, setLetters;

/**
* generates passwords. Uses a closure because we will return function but the link
* with its parent is kept.
* @author Pello Altadill
* @param {number} [length] - optional length
* @return {result}
* @greetz any
*/
var generatePassword = ( 
    function  () {
        var totalLetters = 8;
        var letters = 'abcdef23456789';
        console.log('Ok, initiliazed only once.');
        
        // We define get/set methods
        getTotalLetters = function () {
                        return totalLetters; 
                   };
        setTotalLetters = function (value) {
                        totalLetters = value;
                   };
        getLetters = function () {
                        return letters; 
                   };
        setLetters = function (value) {
                        letters = value;
                   };
                   
        return function () {
            var result = '';
            for (var i = 0;i<totalLetters;i++) {
                result += letters[Math.round(Math.random()*(letters.length-1))];
            }        
            return result;
        }
    
    }
)();

"Ok, initiliazed only once."
generatePassword()
"4c7d4b25"
generatePassword()
"88988ce6"
setTotalLetters(4)
generatePassword()
"ebb5"
generatePassword()
"cfcb"
getTotalLetters()
4
getLetters()
"abcdef23456789"
setLetters('xyz789')
generatePassword()
"7y77"
generatePassword()
"89yy"
generatePassword()
"zz7y"

Iterarion closures

This is a way to crea next(), hasMoreElements()-like iterators in Javascript.

/**
* closure to generate an iterator for arrays
* @author Pello Altadill
* @param {Array} array of elements
* @return {function}
* @greetz any
*/
function iterator(list) {
    var i = 0;
    return function(){
        return list[i++];
    };
}

var nextElement = iterator([15,42,666]);

while (var e = nextElement()) {
    console.log(e);
}

That's all for today. This is but a lame intro, anyway I hope that you find something useful. Mastering javascript functions is important if you want to move on and dive in Objects, prototype, and the like. Greets for you, as always ;)

]]>
http://www.pello.info/index.php/blog/rediscovering-javascript-functions
Rediscovering Javascript basics http://www.pello.info/index.php/blog/rediscovering-javascript-basics http://www.pello.info/index.php/blog/rediscovering-javascript-basics 2015-04-04 23:42:36 pelloxabier http://www.pello.info/index.php/blog/rediscovering-javascript-basics

This will be just another quick reveiw of the Javascript language basics. For any seasoned developer this may seem a pointless effort but perhaps you find something useful, at least to become a js nitpicker or a soon-to-be guru :D.

Javascript properties

Javascript is a weakly typed, interpreted and multi-paradigm (functional,object oriented,..) language in its own way. It is case-sensitive and its basic sintax looks like C. But in a nutshell, its a c without explicit types, where you can store different kind of values in a variable and resize an array with ease.

Comments

the classic C style comments, both single line

// this is a comment

and multiline

/*
This is
a multiline 
comment
*/

For comments and doc generation check jsdoc

Instructions

In javascript, you don't need to end a sentence with a semicolon, unless you want to execute more than one sentence in the same line.

var a = 42

Anyway, people always use to end sentences with a semicolon. By the way, when declaring variables, it is recommended to do it using var because if you omit var your variable will become global!

Deleting elements

There is a delete operator in javascript, which converts any variable to undefined:

var beast = 666;
typeof beast;
"number"
delete beast;
typeof beast;
undefined

Data types

Numbers, Strings and booleans are the primitive data types in Javascript.

Numbers

0
42
-15
3.1415
23e3
Infinity
-Infinity

Strings

A string can be made of single or doble quotes:

"These aren't the droids you're looking for"
'Hello world'
"We'll be \"friends\""

The scape character here is \, and we can use it for special values such as newline, tab, etc..:

Booleans

Two values, as usual

  • true
  • false
Falsy values: some values are interpreted as false:
  • null
  • empty string ""
  • undefined
  • number 0
  • NaN

Other values

There are three other possible data types

Javascript distinguishes between a variables without any value or null value. There is a subtle difference:

  • undefined: this is when a variable does not exist or it is declared but no value has been assigned.
  • Null: a variable exists but its value is simply null.
  • NaN: Not a Number, you get this value when trying to convert something to a number and you fail.
var number = 'example';
typeof number * 666:
NaN

Some curious things about NaN

typeof NaN
number

NaN == NaN
false

2 * undefined
NaN

but
2*null
0

2+null
2

Declaring and initializing variables

Always use var word to declare variables:

var number;
var counter = 0;
var a, b=42, c = 4;
var x,y,z;
x = y = z = 0;

Operators

Arithmetic

No surprises here, operators are the same as C

  • +,-,*,/,%
  • ++,--
  • +=,-=,*=,/=,%=

Comparison

These are the usual operators we find in C, with some additions: <, >, <=, =>

equals

2==2
true
2=='2'
true

not equals

2!=4
true
2!=2
false

equals in value and type:

2==='2'
false
42===42
true

Non-equality

True when values or types are different

2 !== '2'
true
2 !== 2
false

Boolean

The usual stuff as in C:

&& and operator

true && true
true

|| or operator

true || false
true

! not operator

!true
false
!false
true

Arrays

These are indeed much more flexible than C, C++, etc.. we are not stuck to a fixed size and we can resize and reference new indexes of the array as needed.

var numbers = [4,8,2];
console.log(numbers[0]);
4
numbers[2] = 42;
numbers[5] = 666;
console.log(numbers);
[4,8,42,undefined, undefined,666]

They can hold any kind of values:

var festival = [4, true, 'Jon', null, undefined, 666];

Even arrays containing arrays:

var matrix = [[0,5,1],[7,3,2],[3,7,4]];
matrix[0][1];
5
var empty= [];

Control Structures

Same as usual two, condition with parentheses and blocks with curly brackets.

Conditional

if
if (a > 0) {
	console.log('a is greater than 0');
}

For example, test if a variable is defined and has any value different from undefined:

if (typeof someVar !== 'undefined') {
	console.log('someVar is defined ');
}
if-else

Nothing to write home about:

if (a > 0) {
	console.log('a is greater than 0');
} else {
	console.log('a is not greater than 0');
}
Ternary operator

This is the well-known brief formula to code if-else, also known as elvis operator:

var number = (a > 0)?a:42;

is the same as:

if (a > 0) {
	number = a;
} else {
	number = 42;
}
if-else-if

There is no elseif or elsif keyword but you can build it that way:

if (a > 0) {
	console.log('a is greater than 0');
} else if (a < 0) {
	console.log('a is less than 0');
} else {
	console.log('a is 0');
}
switch-case

The same as C but better: we can switch on Strings!

switch (name) {
	case 'Bilbo':
		console.log('You are a hobbit');
		break;
	case 'Legolas':
		console.log('You are an elf');
		break;
	default:
		console.log('Unknown race');
		break;
}

Loops

We find the same structures with some useful variations in for statements

while
while (a > 0) {
	a--;
	console.log('printing a ' + a);
}
do-while

The loop that is executed at least once

do {
	console.log('A printed at least once:' + a);
	a--;
} while (a > 0);
for

The good old for

for (var i = 0;i < 10; i++) {
	console.log('This is i: ' + i);
}
for in

This is some kind of foreach that iterates using the index:

var values = [5,42,666,15];

for (v in values) {
	console.log("index: "+ v + ", value:" + values[v]);
}

Break or continue the loop

Inside a loop instruction we can use two statements:

  1. break: exits current loop inmediately.
  2. continue: ends current iteration and continues to next.

What happens when we try to break from double or even triple loops. We must use tags. If we break to a defined tag, we break the execution and we continue in the same level that the tag resides. Try this:

var i = 0;
var j = 0;
jump:
for ( i = 0;i< 10;i++) {
inside:
    for ( j = 0;j< 10;j++) {
        if (j == 5) {
           continue;
        } else if (i==0 && j==2) {
            continue jump;
        } else if (i==1 && j==6) {
            break;
        } else if (i==2 && j==2) {
            break jump;
        }
        console.log( i + ":" + j);          
    }
}
console.log("out: " + i + ":" + j);
Output:
"0:0"
"0:1"
"1:0"
"1:1"
"1:2"
"1:3"
"1:4"
"2:0"
"2:1"
"out: 2:2"

Functions

Javascript does not distinguish between procedures and functions. There are only functions and all of them must return a value. If no value is returned explicitly, undefined is returned by default

function sayHello() {
	return 'hello';
}

We call to this function by just writing its name with parenthesis:

sayHello();

We can pass parameters to our function:

function sayHelloRepeatedly (repeat) {
	var result = '';
	for (var i = 0;i<repeat;i++) {
		result = result + 'hello';
	}
}

sayHelloRepeatedly(5);
hellohellohellohellohello

If we don't pass a parameter when the function is called, the parameter's value becomes undefined.

We can have more than one parameter:

function saySomethingRepeatedly (repeat, what) {
	var result = '';
	for (var i = 0;i<repeat;i++) {
		result = result +  what;
	}
}

saySomethingRepeatedly('3','Cheese');
CheeseCheeseCheese

Parameter number can be dynamic. We can deal with them using the special arguments variable.

function average () {
    var result = 0;
    var size = 0;
    
    for (var i = 0; i < arguments.length; i++) {
        result = result + arguments[i];
    }
    if (result) {
        result = result / arguments.length;
    }
    
    return result;
    
}

console.log(average());
0
console.log(average(1,4));
2.5
console.log(average(3,3,7,2));
3.75

To sum up.

  • Types: number, String, boolean, null, undefined, NaN, arrays, functions
  • Operators: +,-,*,/,%,=,++,--,+=,-=,*=,/=,%=
  • Comparison: <,==,>,<=,!=,=>,===,!==
  • booleans: &&,||,!
  • others: typeof, instanceof, delete

Code conventions

The general rule is always to be consistent. If you want to follow some rules these by google have proper explanations

]]>

This will be just another quick reveiw of the Javascript language basics. For any seasoned developer this may seem a pointless effort but perhaps you find something useful, at least to become a js nitpicker or a soon-to-be guru :D.

Javascript properties

Javascript is a weakly typed, interpreted and multi-paradigm (functional,object oriented,..) language in its own way. It is case-sensitive and its basic sintax looks like C. But in a nutshell, its a c without explicit types, where you can store different kind of values in a variable and resize an array with ease.

Comments

the classic C style comments, both single line

// this is a comment

and multiline

/*
This is
a multiline 
comment
*/

For comments and doc generation check jsdoc

Instructions

In javascript, you don't need to end a sentence with a semicolon, unless you want to execute more than one sentence in the same line.

var a = 42

Anyway, people always use to end sentences with a semicolon. By the way, when declaring variables, it is recommended to do it using var because if you omit var your variable will become global!

Deleting elements

There is a delete operator in javascript, which converts any variable to undefined:

var beast = 666;
typeof beast;
"number"
delete beast;
typeof beast;
undefined

Data types

Numbers, Strings and booleans are the primitive data types in Javascript.

Numbers

0
42
-15
3.1415
23e3
Infinity
-Infinity

Strings

A string can be made of single or doble quotes:

"These aren't the droids you're looking for"
'Hello world'
"We'll be \"friends\""

The scape character here is \, and we can use it for special values such as newline, tab, etc..:

Booleans

Two values, as usual

  • true
  • false
Falsy values: some values are interpreted as false:
  • null
  • empty string ""
  • undefined
  • number 0
  • NaN

Other values

There are three other possible data types

Javascript distinguishes between a variables without any value or null value. There is a subtle difference:

  • undefined: this is when a variable does not exist or it is declared but no value has been assigned.
  • Null: a variable exists but its value is simply null.
  • NaN: Not a Number, you get this value when trying to convert something to a number and you fail.
var number = 'example';
typeof number * 666:
NaN

Some curious things about NaN

typeof NaN
number

NaN == NaN
false

2 * undefined
NaN

but
2*null
0

2+null
2

Declaring and initializing variables

Always use var word to declare variables:

var number;
var counter = 0;
var a, b=42, c = 4;
var x,y,z;
x = y = z = 0;

Operators

Arithmetic

No surprises here, operators are the same as C

  • +,-,*,/,%
  • ++,--
  • +=,-=,*=,/=,%=

Comparison

These are the usual operators we find in C, with some additions: <, >, <=, =>

equals

2==2
true
2=='2'
true

not equals

2!=4
true
2!=2
false

equals in value and type:

2==='2'
false
42===42
true

Non-equality

True when values or types are different

2 !== '2'
true
2 !== 2
false

Boolean

The usual stuff as in C:

&& and operator

true && true
true

|| or operator

true || false
true

! not operator

!true
false
!false
true

Arrays

These are indeed much more flexible than C, C++, etc.. we are not stuck to a fixed size and we can resize and reference new indexes of the array as needed.

var numbers = [4,8,2];
console.log(numbers[0]);
4
numbers[2] = 42;
numbers[5] = 666;
console.log(numbers);
[4,8,42,undefined, undefined,666]

They can hold any kind of values:

var festival = [4, true, 'Jon', null, undefined, 666];

Even arrays containing arrays:

var matrix = [[0,5,1],[7,3,2],[3,7,4]];
matrix[0][1];
5
var empty= [];

Control Structures

Same as usual two, condition with parentheses and blocks with curly brackets.

Conditional

if
if (a > 0) {
	console.log('a is greater than 0');
}

For example, test if a variable is defined and has any value different from undefined:

if (typeof someVar !== 'undefined') {
	console.log('someVar is defined ');
}
if-else

Nothing to write home about:

if (a > 0) {
	console.log('a is greater than 0');
} else {
	console.log('a is not greater than 0');
}
Ternary operator

This is the well-known brief formula to code if-else, also known as elvis operator:

var number = (a > 0)?a:42;

is the same as:

if (a > 0) {
	number = a;
} else {
	number = 42;
}
if-else-if

There is no elseif or elsif keyword but you can build it that way:

if (a > 0) {
	console.log('a is greater than 0');
} else if (a < 0) {
	console.log('a is less than 0');
} else {
	console.log('a is 0');
}
switch-case

The same as C but better: we can switch on Strings!

switch (name) {
	case 'Bilbo':
		console.log('You are a hobbit');
		break;
	case 'Legolas':
		console.log('You are an elf');
		break;
	default:
		console.log('Unknown race');
		break;
}

Loops

We find the same structures with some useful variations in for statements

while
while (a > 0) {
	a--;
	console.log('printing a ' + a);
}
do-while

The loop that is executed at least once

do {
	console.log('A printed at least once:' + a);
	a--;
} while (a > 0);
for

The good old for

for (var i = 0;i < 10; i++) {
	console.log('This is i: ' + i);
}
for in

This is some kind of foreach that iterates using the index:

var values = [5,42,666,15];

for (v in values) {
	console.log("index: "+ v + ", value:" + values[v]);
}

Break or continue the loop

Inside a loop instruction we can use two statements:

  1. break: exits current loop inmediately.
  2. continue: ends current iteration and continues to next.

What happens when we try to break from double or even triple loops. We must use tags. If we break to a defined tag, we break the execution and we continue in the same level that the tag resides. Try this:

var i = 0;
var j = 0;
jump:
for ( i = 0;i< 10;i++) {
inside:
    for ( j = 0;j< 10;j++) {
        if (j == 5) {
           continue;
        } else if (i==0 && j==2) {
            continue jump;
        } else if (i==1 && j==6) {
            break;
        } else if (i==2 && j==2) {
            break jump;
        }
        console.log( i + ":" + j);          
    }
}
console.log("out: " + i + ":" + j);
Output:
"0:0"
"0:1"
"1:0"
"1:1"
"1:2"
"1:3"
"1:4"
"2:0"
"2:1"
"out: 2:2"

Functions

Javascript does not distinguish between procedures and functions. There are only functions and all of them must return a value. If no value is returned explicitly, undefined is returned by default

function sayHello() {
	return 'hello';
}

We call to this function by just writing its name with parenthesis:

sayHello();

We can pass parameters to our function:

function sayHelloRepeatedly (repeat) {
	var result = '';
	for (var i = 0;i<repeat;i++) {
		result = result + 'hello';
	}
}

sayHelloRepeatedly(5);
hellohellohellohellohello

If we don't pass a parameter when the function is called, the parameter's value becomes undefined.

We can have more than one parameter:

function saySomethingRepeatedly (repeat, what) {
	var result = '';
	for (var i = 0;i<repeat;i++) {
		result = result +  what;
	}
}

saySomethingRepeatedly('3','Cheese');
CheeseCheeseCheese

Parameter number can be dynamic. We can deal with them using the special arguments variable.

function average () {
    var result = 0;
    var size = 0;
    
    for (var i = 0; i < arguments.length; i++) {
        result = result + arguments[i];
    }
    if (result) {
        result = result / arguments.length;
    }
    
    return result;
    
}

console.log(average());
0
console.log(average(1,4));
2.5
console.log(average(3,3,7,2));
3.75

To sum up.

  • Types: number, String, boolean, null, undefined, NaN, arrays, functions
  • Operators: +,-,*,/,%,=,++,--,+=,-=,*=,/=,%=
  • Comparison: <,==,>,<=,!=,=>,===,!==
  • booleans: &&,||,!
  • others: typeof, instanceof, delete

Code conventions

The general rule is always to be consistent. If you want to follow some rules these by google have proper explanations

]]>
http://www.pello.info/index.php/blog/rediscovering-javascript-basics
Rediscovering Javascript http://www.pello.info/index.php/blog/rediscovering-javascript http://www.pello.info/index.php/blog/rediscovering-javascript 2015-04-02 23:05:15 pelloxabier http://www.pello.info/index.php/blog/rediscovering-javascript

When Node.JS server side engine came into play along with some other ideas like noSQL databases , javascript language definitely got my attention. These are technologies that turned inside out the way we can develop applications after years and years of php, jsp, aspx and the like querying data through SQL. Changes also came to the client side of the web since AJAX started playing a crucial role in massive apps such as gmail. After the browser wars, javascript seemed to be in an abandoned position in favor of other animated horrors made with flash. But fortunately, now there is a clear rebirth of this language with a plethora of frameworks to develop single page applications and an ever growing helper libraries covering all kind of tasks you can think of. If something exists for other languages you can certainly take for granted that some guy has a github hosted and forked project providing the same functionality. Ant/Maven and Grunt for example.

It is also remarkable that this is a community that does not need any well-known MegaCorportarion supporting them. Javascript has increasingly tiptoed to the exclusive group of the most required language on its own right. From support libraries like jquery to MVC frameworks such as Backbone o Angular, client side web has become so important that the classic web developer profile is now split between back-end and front-end developers; and mastering both sides of the web is becoming more and more difficult every day. Anybody who thinks that javascript was but a toy should be ready to rediscover this rich and active ecosystem. And let me whisper you a secret: forget Java or any other interpreted languages out there, relevant or not. Javascript is everywhere, because wherever a web browser is, a JS intepreter must be present no matter if it is an iPhone or your latest Ubuntu box. And anyway, if needed Node is available for many platforms.

But let's get down to business. I guess that you are reading this on a browser. Good! You are ready to start right away. Open the javascript console and you will be able to write and try code. Your best options are:

  • Firexox: the built-in web console or using the Firebug add-on, where you can write multiline code just pressing the up arrow on the right of the console. Remember the old days when you only have a console to see the errors? Now you can enter commands and even Tab to get code completion and proposals.
  • Chrome has also a built-in developer tool. Go to menu or press Ctrl-Shift-J. If you need to write multiple lines of code just press Shift-Enter. Then press just Enter to run.
  • JsFiddle or JsBin website. If you want yo use your browser screen directly this kind of website is the rightful choice. It allows you to include the most popular frameworks to code around.
  • Explorer, yes can you believe that? For those who lived through the nineties it is unbelievable this new attitude. Remember when you wanted to see the source code and notepad was opened? Now Explorer comes with some developer tools. It still sucks big time anyway.

There are other choices like Jetbrains Webstorm of course, but if you want to start quickly and just to learn or rediscover this language, stick to your favorite browser. Javascript seems simple, but when things get complex... hold tight because this could turn into a white-knuckle ride in the web roller coaster.

]]>

When Node.JS server side engine came into play along with some other ideas like noSQL databases , javascript language definitely got my attention. These are technologies that turned inside out the way we can develop applications after years and years of php, jsp, aspx and the like querying data through SQL. Changes also came to the client side of the web since AJAX started playing a crucial role in massive apps such as gmail. After the browser wars, javascript seemed to be in an abandoned position in favor of other animated horrors made with flash. But fortunately, now there is a clear rebirth of this language with a plethora of frameworks to develop single page applications and an ever growing helper libraries covering all kind of tasks you can think of. If something exists for other languages you can certainly take for granted that some guy has a github hosted and forked project providing the same functionality. Ant/Maven and Grunt for example.

It is also remarkable that this is a community that does not need any well-known MegaCorportarion supporting them. Javascript has increasingly tiptoed to the exclusive group of the most required language on its own right. From support libraries like jquery to MVC frameworks such as Backbone o Angular, client side web has become so important that the classic web developer profile is now split between back-end and front-end developers; and mastering both sides of the web is becoming more and more difficult every day. Anybody who thinks that javascript was but a toy should be ready to rediscover this rich and active ecosystem. And let me whisper you a secret: forget Java or any other interpreted languages out there, relevant or not. Javascript is everywhere, because wherever a web browser is, a JS intepreter must be present no matter if it is an iPhone or your latest Ubuntu box. And anyway, if needed Node is available for many platforms.

But let's get down to business. I guess that you are reading this on a browser. Good! You are ready to start right away. Open the javascript console and you will be able to write and try code. Your best options are:

  • Firexox: the built-in web console or using the Firebug add-on, where you can write multiline code just pressing the up arrow on the right of the console. Remember the old days when you only have a console to see the errors? Now you can enter commands and even Tab to get code completion and proposals.
  • Chrome has also a built-in developer tool. Go to menu or press Ctrl-Shift-J. If you need to write multiple lines of code just press Shift-Enter. Then press just Enter to run.
  • JsFiddle or JsBin website. If you want yo use your browser screen directly this kind of website is the rightful choice. It allows you to include the most popular frameworks to code around.
  • Explorer, yes can you believe that? For those who lived through the nineties it is unbelievable this new attitude. Remember when you wanted to see the source code and notepad was opened? Now Explorer comes with some developer tools. It still sucks big time anyway.

There are other choices like Jetbrains Webstorm of course, but if you want to start quickly and just to learn or rediscover this language, stick to your favorite browser. Javascript seems simple, but when things get complex... hold tight because this could turn into a white-knuckle ride in the web roller coaster.

]]>
http://www.pello.info/index.php/blog/rediscovering-javascript
Migrate from google code to github or bitbucket in easy steps http://www.pello.info/index.php/blog/migrate-from-google-code-to-github-or-bitbucket-in-easy-steps http://www.pello.info/index.php/blog/migrate-from-google-code-to-github-or-bitbucket-in-easy-steps 2015-03-13 10:17:53 pelloxabier http://www.pello.info/index.php/blog/migrate-from-google-code-to-github-or-bitbucket-in-easy-steps

Google code disappears

Repent, the end is near. Google has just announced that they are shutting down google code project hosting. In the email of the announcement they make some suggestions to find a new house for your code such as bitbucket or github. I hope that they have been warned in order to be ready for a massive repository creation from the upcoming exodus of coder refugees.

At the time of writing this, there is a button to automate the migration only to github but it is NOT working due to the high amount of traffic and workload that they are experiencing.

But you can still move your stuff manually. Here are some easy-to-follow steps to move your code from google to github just using your command line.

0 .Go to google code

It is not as obvious as it may seem. Once you log in google is impossible to find a simple link to see your projects. Google is not specially good at usability, but hey, when your shares are valued at >500$ who gives a fuck. Nevermind, go to https://code.google.com/hosting/ and check My favorites

1. Checkout project

Enter into the project you want to migrate and select Source. Copy the command to checkout your code, with read-only is enough.

For example for: http://code.google.com/p/erps-2dam-4vientos/

Go to source and:

svn checkout http://erps-2dam-4vientos.googlecode.com/svn/trunk/ erps-2dam-4vientos-read-only

2. Do some cleaning

Enter the directory and erase all svn files

find . -type d -name .svn -exec rm -rf {} +

Remove any other unnecessary stuff, binaries, jars,.. and the like.

3. Create repo on github or bitbucket

They both have free repository services, sign up and you can create repos.

4. Clone the repo

Once your repo is created they will provide you with a clone url or even the exact command you need to clone the repo locally.

git clone http://clone...

5. Copy files to your local git project directory

Move/copy files from your google-code local copy to git local copy.

mv google-code-dir/* git-project-dir/

6. Add and commit code

Now it's time to add to git the newly copied code files. You can achieve this with to easy commands, Bob Marley style:

git add *
git commit -m 'Exodus: Movement of Jah people! Oh-oh-oh, yea-eah!'

7. Push to remote

Final step to have your code online again and safe for [hopefully] [some] years to come. You'll be prompted to enter your username and password.

git push origin master

Greets for you, lucky bitbucket user. Your nice arse is safe at the moment

]]>

Google code disappears

Repent, the end is near. Google has just announced that they are shutting down google code project hosting. In the email of the announcement they make some suggestions to find a new house for your code such as bitbucket or github. I hope that they have been warned in order to be ready for a massive repository creation from the upcoming exodus of coder refugees.

At the time of writing this, there is a button to automate the migration only to github but it is NOT working due to the high amount of traffic and workload that they are experiencing.

But you can still move your stuff manually. Here are some easy-to-follow steps to move your code from google to github just using your command line.

0 .Go to google code

It is not as obvious as it may seem. Once you log in google is impossible to find a simple link to see your projects. Google is not specially good at usability, but hey, when your shares are valued at >500$ who gives a fuck. Nevermind, go to https://code.google.com/hosting/ and check My favorites

1. Checkout project

Enter into the project you want to migrate and select Source. Copy the command to checkout your code, with read-only is enough.

For example for: http://code.google.com/p/erps-2dam-4vientos/

Go to source and:

svn checkout http://erps-2dam-4vientos.googlecode.com/svn/trunk/ erps-2dam-4vientos-read-only

2. Do some cleaning

Enter the directory and erase all svn files

find . -type d -name .svn -exec rm -rf {} +

Remove any other unnecessary stuff, binaries, jars,.. and the like.

3. Create repo on github or bitbucket

They both have free repository services, sign up and you can create repos.

4. Clone the repo

Once your repo is created they will provide you with a clone url or even the exact command you need to clone the repo locally.

git clone http://clone...

5. Copy files to your local git project directory

Move/copy files from your google-code local copy to git local copy.

mv google-code-dir/* git-project-dir/

6. Add and commit code

Now it's time to add to git the newly copied code files. You can achieve this with to easy commands, Bob Marley style:

git add *
git commit -m 'Exodus: Movement of Jah people! Oh-oh-oh, yea-eah!'

7. Push to remote

Final step to have your code online again and safe for [hopefully] [some] years to come. You'll be prompted to enter your username and password.

git push origin master

Greets for you, lucky bitbucket user. Your nice arse is safe at the moment

]]>
http://www.pello.info/index.php/blog/migrate-from-google-code-to-github-or-bitbucket-in-easy-steps
Vagrant: hello box, thank you for coming http://www.pello.info/index.php/blog/vagrant-hello-box-thank-you-for-coming http://www.pello.info/index.php/blog/vagrant-hello-box-thank-you-for-coming 2014-08-13 00:35:34 pelloxabier http://www.pello.info/index.php/blog/vagrant-hello-box-thank-you-for-coming

Vagrant is a virtual machines management tool that allows us to easily create, run, configure and share customized virtual systems. The main goal of Vagrant is to provide a centralized way to share preconfigured virtual machines for software developers. In development teams, all members must share not only and up-to-date project source, but also the same system configuration: database management systems, web servers, application servers, IDEs, development kits,... It is almost impossible to keep them identical in each station, not to mention the same specific versions of each program needed. Another issue that comes to mind if you have ever suffered this is when your system crashed or you simply upgrade your hardware, or some IDE requires the latest operative system from Redmond: you will start again from scratch installing all the components you need to have your environment ready to work. This is a sort of myth of sisyphus adapted to coders.

Virtualization comes to the rescue! but this is not just about sharing a common virtual machine among developers. Vagrant wraps the virtualization system, and so we are not necessarily tied to any of them. Vagrant supports Virtual Box (easily available), VMWare and even Amazon EC2, is easy to get into it.

Up and running

In two easy steps we init a vagrant machine (a default 64bit box) and then we just boot it with vagrant up. The first time the box must be downloaded

d:\vm\vagrant init hashicorp/precise32
...
d:\vm\vagrant up

The first command will create a Vagrant configuration file, nice and self-documented. This is how it looks like in a windows host:

Vagrant running
Automated configuration

Ok, we get a basic machine but what happens with the configuration. Vagrant can take advantadge of powerful configuration tools suchs as chef and puppet. These two deserve not a post but one book each. In a nutshell, this kind of software automates machine configuration; for programming environments there are already tools that using declarative description you get code. In the same way, sysadmins now are able to deploy several servers perfectly configured in no time, just writing configuration (and shareable) files. That easy.

Going social

Even developers communicate and share (code), but mainly between them, though. And so for development boxes. Officialy available we have the Vagrant Cloud, were we can grab popular boxes with some rating information included. It's very easy to join the cloud and create your own boxes. You'll just face one little problem, you must upload your box somewhere. Other reference site could be Vagrant Box, with many different linux flavors for you to pick. There are, also, other propietary boxes available.

Educational purposes

Maybe in a software development company or department you just the same kind of environment all the time. But Vagrant could be a really great tool to use at school. Depending on the subjects students have to switch their environments and they will drive you crazy because two of them don't have the latest JVM or the usual suspects don't know even how to switch off their windows8. You could prepare one Vagrant box, perfectly configured for each subject, even for each specific unit of the same subject. For example, preparing an Android development environment it's really a pain in the ass. Instead of stuffing one single machine with all the software you need, a good use of Vagrant could avoid conflicts and guarantee that all students are using exactly the same environment. As easy as pie.

It is not unusual that you try to learn something new and that leads you to learn many other things. Here I have written a bunch of names to be aware of, and I hope that this post helps as a reminder for the near future. Greetz 4 u.

]]>

Vagrant is a virtual machines management tool that allows us to easily create, run, configure and share customized virtual systems. The main goal of Vagrant is to provide a centralized way to share preconfigured virtual machines for software developers. In development teams, all members must share not only and up-to-date project source, but also the same system configuration: database management systems, web servers, application servers, IDEs, development kits,... It is almost impossible to keep them identical in each station, not to mention the same specific versions of each program needed. Another issue that comes to mind if you have ever suffered this is when your system crashed or you simply upgrade your hardware, or some IDE requires the latest operative system from Redmond: you will start again from scratch installing all the components you need to have your environment ready to work. This is a sort of myth of sisyphus adapted to coders.

Virtualization comes to the rescue! but this is not just about sharing a common virtual machine among developers. Vagrant wraps the virtualization system, and so we are not necessarily tied to any of them. Vagrant supports Virtual Box (easily available), VMWare and even Amazon EC2, is easy to get into it.

Up and running

In two easy steps we init a vagrant machine (a default 64bit box) and then we just boot it with vagrant up. The first time the box must be downloaded

d:\vm\vagrant init hashicorp/precise32
...
d:\vm\vagrant up

The first command will create a Vagrant configuration file, nice and self-documented. This is how it looks like in a windows host:

Vagrant running
Automated configuration

Ok, we get a basic machine but what happens with the configuration. Vagrant can take advantadge of powerful configuration tools suchs as chef and puppet. These two deserve not a post but one book each. In a nutshell, this kind of software automates machine configuration; for programming environments there are already tools that using declarative description you get code. In the same way, sysadmins now are able to deploy several servers perfectly configured in no time, just writing configuration (and shareable) files. That easy.

Going social

Even developers communicate and share (code), but mainly between them, though. And so for development boxes. Officialy available we have the Vagrant Cloud, were we can grab popular boxes with some rating information included. It's very easy to join the cloud and create your own boxes. You'll just face one little problem, you must upload your box somewhere. Other reference site could be Vagrant Box, with many different linux flavors for you to pick. There are, also, other propietary boxes available.

Educational purposes

Maybe in a software development company or department you just the same kind of environment all the time. But Vagrant could be a really great tool to use at school. Depending on the subjects students have to switch their environments and they will drive you crazy because two of them don't have the latest JVM or the usual suspects don't know even how to switch off their windows8. You could prepare one Vagrant box, perfectly configured for each subject, even for each specific unit of the same subject. For example, preparing an Android development environment it's really a pain in the ass. Instead of stuffing one single machine with all the software you need, a good use of Vagrant could avoid conflicts and guarantee that all students are using exactly the same environment. As easy as pie.

It is not unusual that you try to learn something new and that leads you to learn many other things. Here I have written a bunch of names to be aware of, and I hope that this post helps as a reminder for the near future. Greetz 4 u.

]]>
http://www.pello.info/index.php/blog/vagrant-hello-box-thank-you-for-coming
Persistent session control in Node.js with express 4 http://www.pello.info/index.php/blog/persistent-session-control-in-node-js-with-express-4 http://www.pello.info/index.php/blog/persistent-session-control-in-node-js-with-express-4 2014-08-03 00:08:50 pelloxabier http://www.pello.info/index.php/blog/persistent-session-control-in-node-js-with-express-4 In this series of posts I'm trying to show, in the simplest way possible, how to develop a web application in Node.js adding all the features that in other environments we take for granted: database access, form validation, i18n, and of course session management. Express is the framework of choice for this purpose, the problem is that maybe many information you find out there may be deprecated or useless since express 4 was released. Here I'm trying to use the latest (express4) and the coolest, but in any case in the months to come this information may be crappy. As some dear friend of mine says talk is cheap, show me the code, so let's get down to the nitty-gritty details.

Session control in Express4
You shall not pass today, tomorrow who knows.

If we want to control the access to certain functions of our application or if we need multiuser support to distinguish the activities of those users we need some kind of session control. Node.js based web servers behave as any other web server so we don't have a permanent connection to establish such mechanism. But, as many other platforms do, express can deal with cookies and as you should know, these are commonly used to to simulate a permanent state which is, finally, a session.

Beware code samples from a year ago, unless you are using older versions of express. Since version 4 there are many modules that now are not included in express (almost all but static file server) and you have to grab them independently: express-session is the one we need to be able to access session variables with req.session. It has many, many options, expiration, security, e.a.

Session persistence

Cookie based sessions will depend on Node.js server process. If we need them to persist without any dependency on Node we can store session information in a database. This is very easy to apply, and in this case as we are using express and mongoose the package named mongoose-session becomes the perfect candidate to do the job. Just require it and apply as a parameter to the session system.

This is how it looks our app.js

Exposing session variables in jade templates

Something that many posts and tutorials tend to omit is that, if you need to expose session values in the view (jade in our case), you need to add this middleware:

That will allow us now to use session.login in our template, something that will come in handy when we want to add a 'hello -yourname-' in our web page when the user is logged or if we want to show different links depending on the session status.

Login and session start

Ok, our web server now is ready to support sessions, so it's time to create a login or sign in view and the routes for session management. This is how the view looks like, is but a simple login form.

In the route is where we check the login. To keep this code simple we are using a hardcoded account to check if login is correct or not. When it is successful, we simply store a session variable that will be later used to check with a middleware if the session is valid or not. Mongoose-session package will save session information automagically in a collection that by default is called session. After that, the flow is redirected to the guestbook page. If login is not correct, we simply redirect to sign in page again.

Protecting pages and checking session status

All of this session stuff is intended to control the access to our guestbook, something that we can do in a very simple and easy way that suits perfectly in an express application. We create a middleware that simply checks if session is started or not. These few lines of code will do the trick:

And now, in any page, or more accurately, in any express route that we want to protect, we just add this middleware as a parameter for that route.

Is that simple. Now we can imagine other middlewares to apply ACL depending on user roles for example.

Keep the guestbook clean

In every web application we need to prevent any dangerous data to be persisted in our database, because it could go back to everybody as a XSS attack. Here I'm simply using an html sanitizer inside a helper that could be used on demand to clean user input. The helper concept is common among many web frameworks, and it is not unusual to see such utilities in Node.js applications.

As you can see in the last piece of code, now before we save data into MongoDB we can guarantee that no html shall pass.

]]>
In this series of posts I'm trying to show, in the simplest way possible, how to develop a web application in Node.js adding all the features that in other environments we take for granted: database access, form validation, i18n, and of course session management. Express is the framework of choice for this purpose, the problem is that maybe many information you find out there may be deprecated or useless since express 4 was released. Here I'm trying to use the latest (express4) and the coolest, but in any case in the months to come this information may be crappy. As some dear friend of mine says talk is cheap, show me the code, so let's get down to the nitty-gritty details.

Session control in Express4
You shall not pass today, tomorrow who knows.

If we want to control the access to certain functions of our application or if we need multiuser support to distinguish the activities of those users we need some kind of session control. Node.js based web servers behave as any other web server so we don't have a permanent connection to establish such mechanism. But, as many other platforms do, express can deal with cookies and as you should know, these are commonly used to to simulate a permanent state which is, finally, a session.

Beware code samples from a year ago, unless you are using older versions of express. Since version 4 there are many modules that now are not included in express (almost all but static file server) and you have to grab them independently: express-session is the one we need to be able to access session variables with req.session. It has many, many options, expiration, security, e.a.

Session persistence

Cookie based sessions will depend on Node.js server process. If we need them to persist without any dependency on Node we can store session information in a database. This is very easy to apply, and in this case as we are using express and mongoose the package named mongoose-session becomes the perfect candidate to do the job. Just require it and apply as a parameter to the session system.

This is how it looks our app.js

Exposing session variables in jade templates

Something that many posts and tutorials tend to omit is that, if you need to expose session values in the view (jade in our case), you need to add this middleware:

That will allow us now to use session.login in our template, something that will come in handy when we want to add a 'hello -yourname-' in our web page when the user is logged or if we want to show different links depending on the session status.

Login and session start

Ok, our web server now is ready to support sessions, so it's time to create a login or sign in view and the routes for session management. This is how the view looks like, is but a simple login form.

In the route is where we check the login. To keep this code simple we are using a hardcoded account to check if login is correct or not. When it is successful, we simply store a session variable that will be later used to check with a middleware if the session is valid or not. Mongoose-session package will save session information automagically in a collection that by default is called session. After that, the flow is redirected to the guestbook page. If login is not correct, we simply redirect to sign in page again.

Protecting pages and checking session status

All of this session stuff is intended to control the access to our guestbook, something that we can do in a very simple and easy way that suits perfectly in an express application. We create a middleware that simply checks if session is started or not. These few lines of code will do the trick:

And now, in any page, or more accurately, in any express route that we want to protect, we just add this middleware as a parameter for that route.

Is that simple. Now we can imagine other middlewares to apply ACL depending on user roles for example.

Keep the guestbook clean

In every web application we need to prevent any dangerous data to be persisted in our database, because it could go back to everybody as a XSS attack. Here I'm simply using an html sanitizer inside a helper that could be used on demand to clean user input. The helper concept is common among many web frameworks, and it is not unusual to see such utilities in Node.js applications.

As you can see in the last piece of code, now before we save data into MongoDB we can guarantee that no html shall pass.

]]>
http://www.pello.info/index.php/blog/persistent-session-control-in-node-js-with-express-4
Node.js internationalization and form validation http://www.pello.info/index.php/blog/node-js-internationalization-and-form-validation http://www.pello.info/index.php/blog/node-js-internationalization-and-form-validation 2014-08-01 00:27:41 pelloxabier http://www.pello.info/index.php/blog/node-js-internationalization-and-form-validation In any application, no matter the languages or the environment you are using, it is always necessary to ensure that all data is validated before we try any operation. It's tedious, boring and maybe you prefer to focus on more interesting things but you may fear not only hackers, but also the users who from time to time become true hackers without been really aware of it: just applying unexpected input. For instance a form field could ask for the zip code and a regular user could answer (sincerely) 'I don't know'. And he is being honest but at the same time he is creating an exception and blowing out your super-duper node server.

Form validation

In addition to that and in order to be nice with a wider range of users you have to offer internationalization support. Once again, a boring but a mandatory task to take into account when you are dealing with the views. In this post I'll show one approach to solve these issues node.js trying to keep the code simple. Let's start with i18n.

Internationalization in Node.js

For Node.js and in general for any javascript based software we have then i18next package. It comes with all you need to write multilingual applications, many available options for the language file format and many niceties as well. i18next can be used in both server and client side javascript. In this case I'll show just the translation files format, how to init i18next and how to apply in jade templates. In the event that you're using Angular (or maybe something not so mainstream :P) framework in the frontend, it is possible to reuse the work done in server side.

Language files

In the root of your project, just place a directory called locales and inside it one directory for each language you give support to (locales/en, locales/es), including locales/dev/ which is the lang by default. And inside each directory, place a json file called translation.json. So we are using json format, but there are other formats available, and many other options including namespaces support.

This is how the translation.json file looks like. Note that you can organize translations in groups

Applying i18next

In our main program, app.js, we will have to require, init and apply i18next to our express application to make it available for jade templates. This is app.js now, some init alternatives are commented. The loading of the translation files is done asynchronously.

This is how we apply i18n in a jade template using function t(key), where key must have an entry in the translation files.

Simple form validation

As simple as using validation facilities from the mongoose driver. There are another options but in this case I wanted to make use of something that I already have instead of trying other packages. Check these modules if you need something else or if you have forms that have nothing to do with an underlying database. Anyway, if we are using mongoose, we'll have to create validations.

MongoDB is a schemaless document-oriented database and it can handle anything: each row in a collection could be completely different. However, Mongoose driver is much more than a simple way to access a database: it forces you to define schemas to map each collection in database, where at least you have to detail fields and data types. In a way, that is a first defense line. In those schema definitions (which deserve another long post devoted to mongoose exclusively) is where we can apply validations (built-in and custom), limits and even define custom error messages! Here I'm improving the schema for the guestbook collection.

Internationalization in mongoose validation messages

I'm applying i18n in the mongoose schema in a ... cryptic way. There is a problem if we try to use the i18next.t(key) function to apply messages in schemas. In the main app.js we are loading express routes. Routes are requiring schemas and as i18next are not loaded synchronously (and init options for that are not working as expected) so those t(key) calls in mongoose models will fail. We could refactor and reshape the main app.js, we could maybe use packages to force synchronous behaviour, but It is much more easier to use the key from translation files, which are simple strings.

This is the guestbook.jade template, now with some error handling conditionals to show error messages. Mongoose stores all validation information in an err object which we simply pass to this jade template to be displayed.

And finally the router where we get validation data from mongoose and we move to the template to be rendered.

Once again I tried to keep main app.js simple. There may be many other (and better) recipes because Node.js is like a bazaar with thousands of very active contributors. Greets to any.

]]>
In any application, no matter the languages or the environment you are using, it is always necessary to ensure that all data is validated before we try any operation. It's tedious, boring and maybe you prefer to focus on more interesting things but you may fear not only hackers, but also the users who from time to time become true hackers without been really aware of it: just applying unexpected input. For instance a form field could ask for the zip code and a regular user could answer (sincerely) 'I don't know'. And he is being honest but at the same time he is creating an exception and blowing out your super-duper node server.

Form validation

In addition to that and in order to be nice with a wider range of users you have to offer internationalization support. Once again, a boring but a mandatory task to take into account when you are dealing with the views. In this post I'll show one approach to solve these issues node.js trying to keep the code simple. Let's start with i18n.

Internationalization in Node.js

For Node.js and in general for any javascript based software we have then i18next package. It comes with all you need to write multilingual applications, many available options for the language file format and many niceties as well. i18next can be used in both server and client side javascript. In this case I'll show just the translation files format, how to init i18next and how to apply in jade templates. In the event that you're using Angular (or maybe something not so mainstream :P) framework in the frontend, it is possible to reuse the work done in server side.

Language files

In the root of your project, just place a directory called locales and inside it one directory for each language you give support to (locales/en, locales/es), including locales/dev/ which is the lang by default. And inside each directory, place a json file called translation.json. So we are using json format, but there are other formats available, and many other options including namespaces support.

This is how the translation.json file looks like. Note that you can organize translations in groups

Applying i18next

In our main program, app.js, we will have to require, init and apply i18next to our express application to make it available for jade templates. This is app.js now, some init alternatives are commented. The loading of the translation files is done asynchronously.

This is how we apply i18n in a jade template using function t(key), where key must have an entry in the translation files.

Simple form validation

As simple as using validation facilities from the mongoose driver. There are another options but in this case I wanted to make use of something that I already have instead of trying other packages. Check these modules if you need something else or if you have forms that have nothing to do with an underlying database. Anyway, if we are using mongoose, we'll have to create validations.

MongoDB is a schemaless document-oriented database and it can handle anything: each row in a collection could be completely different. However, Mongoose driver is much more than a simple way to access a database: it forces you to define schemas to map each collection in database, where at least you have to detail fields and data types. In a way, that is a first defense line. In those schema definitions (which deserve another long post devoted to mongoose exclusively) is where we can apply validations (built-in and custom), limits and even define custom error messages! Here I'm improving the schema for the guestbook collection.

Internationalization in mongoose validation messages

I'm applying i18n in the mongoose schema in a ... cryptic way. There is a problem if we try to use the i18next.t(key) function to apply messages in schemas. In the main app.js we are loading express routes. Routes are requiring schemas and as i18next are not loaded synchronously (and init options for that are not working as expected) so those t(key) calls in mongoose models will fail. We could refactor and reshape the main app.js, we could maybe use packages to force synchronous behaviour, but It is much more easier to use the key from translation files, which are simple strings.

This is the guestbook.jade template, now with some error handling conditionals to show error messages. Mongoose stores all validation information in an err object which we simply pass to this jade template to be displayed.

And finally the router where we get validation data from mongoose and we move to the template to be rendered.

Once again I tried to keep main app.js simple. There may be many other (and better) recipes because Node.js is like a bazaar with thousands of very active contributors. Greets to any.

]]>
http://www.pello.info/index.php/blog/node-js-internationalization-and-form-validation
Keeping Node.js app.js clean + custom middleware for express http://www.pello.info/index.php/blog/keeping-node-js-app-js-clean-custom-middleware-for-express http://www.pello.info/index.php/blog/keeping-node-js-app-js-clean-custom-middleware-for-express 2014-07-26 23:03:41 pelloxabier http://www.pello.info/index.php/blog/keeping-node-js-app-js-clean-custom-middleware-for-express

This post has two purposes: to continue the previous one showing ways to improve the organization of routes and secondly to see how to add your own middleware to an express application.

The previous version have a problem when it comes to the routes. We require all of them with a single require command but we were applying them one by one.

var routes = require('./routes');
...
// We set routes
app.use('/', routes.home);
app.use('/guestbook', routes.guestbook);
Use a contructor in routes/index.js

There Is More Than One Way To Do It claims the Programming Perl book on the cover. Something that, undoubtedly, fits Node.js. There is more than one style in Node-foo, and I guess that you have to choose the way that better fits your needs. My need here was to minimize the code to initialize the routes in the main file of the Node.js express application. We change the routes/index.js to have a constructor with a parameter: the express app itself

This is routes/index.js

/**
 * routes/index.js
 * All routes are here to import all of them just with one command
 * in the main app.js
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
var home = require('./home');
var guestbook = require('./guestbook');

module.exports = function (app) {
	home(app);
	guestbook(app);
}

See those calls to home and guestbook? we are passing again the express app instance to each route file, where we also change its shape to get that parameter. Be careful! now we have to specify the complete route to '/guestbook/', something that in fact makes everything much more clear

/**
 * routes/guestbook.js
 * The router for guestbook operations.
 * Keep in mind that here '/' refers to '/guestbook/'
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
var mongoose = require('mongoose');
var GuestBook = mongoose.model('GuestBook');

module.exports = function (app) {

    /**
    * get
    * GETs all guestbook data.
    */
    app.get('/guestbook/', function(req, res) {
    ...
}

home.js does the same

/**
 * routes/home.js
 * The home page, just renders the jade template
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
module.exports = function (app) {

	app.get('/', function(req, res) {
	    res.render('index.jade' , {title: 'Home page'});
	});

}

And now, this is how the main app.js looks like. Instead of using each route separately, now it's enough to do it once. In this example may seem a useless effort, but when your app evolves to have many different routes dispersed in many files we will add all of them with just one command, keeping our main app.js nice and clean.

/**
* app.js
* Main entrypoint for the app
* https://github.com/pello-io/simple-express-mongoose
* Pello Altadill - http://pello.info
*/
var express = require('express');
var bodyParser = require('body-parser');

var models = require('./models');
var routes = require('./routes');
var middleware = require('./middleware');

var app = express();

// If we want to use post data:
app.use(bodyParser());

// We set middlewares
middleware(app);

// We set all the routes with one single call
routes(app);

// We set static content
app.use(express.static('public'));

// And there we go, listening on port 3000
app.listen(3000, function () {
    console.log('now listening on http://localhost:3000');
});
Creating custom middleware

If you are using connect or express then it's probably making use of more than one middleware. In a nutshell, the middleware is some code that is executed between the request and te response in a Node.js web application. Therefore, whenever you call app.use(whatever) you are already applying middleware like routes, bodyParser, etc...

Some dummy middlewares

Let's create some middleware for testing. The first will just log the requests made to our server and the second will log a message. The second its useful only to observe the way the middlewares are chained for each request. As we can have more than one custom middleware and following the same style of the routes and models, we'll create a folder called middleware with an index.js file that will load and apply all the middlewares.

This is how the logrequest middleware looks like. Don't forget the next() call, or the request will not go on to next middleware!!!

/**
* logrequest
* this just logs every request to console
*/

module.exports = function logRequest (req, res, next) {
  console.log('request received: ');
  console.log("["+req.method+"] " + req.url);
  console.log(req.body);
  // and go on... if you don't call next the request will hang
  next();
}

And this is the dummy middleware

/**
* dummyddleware.js
* A dummy middleware just to see the order it is being called
*/

module.exports = function dummyddleware (req,res, next) {
	console.log('Dummy middleware');
	next();
}

And the index.js that applies them both to the expres app

/**
 * middleware/index.js
 * All middleware are here to import all of them just with one command
 * in the main app.js
 * Note that maybe this is not always desirable if you want to apply
 * any other middleware in a different order into app.js file.
 * @greetz for any
 */
var logrequest = require('./logrequest');
var dummyddleware = require('./dummyddleware');

module.exports = function (app) {
	app.use(logrequest);
	app.use(dummyddleware);
}

Finally as we have seen before, in the main entry-point we can just add

var middleware = require('./middleware');
...
// We set middleware
middleware(app);

At the time of writing this I'm receiving very valuable feedback about how to organize your projects, even with fullstack app generators. Which one is the best? It's the usual devious question that comes from a sales manager or the like. It depends on the project nature, don't you think?

You can clone, download(at this point of development), copy-paste this project from git. Don't forget to get the required node modules to make it work!

]]>

This post has two purposes: to continue the previous one showing ways to improve the organization of routes and secondly to see how to add your own middleware to an express application.

The previous version have a problem when it comes to the routes. We require all of them with a single require command but we were applying them one by one.

var routes = require('./routes');
...
// We set routes
app.use('/', routes.home);
app.use('/guestbook', routes.guestbook);
Use a contructor in routes/index.js

There Is More Than One Way To Do It claims the Programming Perl book on the cover. Something that, undoubtedly, fits Node.js. There is more than one style in Node-foo, and I guess that you have to choose the way that better fits your needs. My need here was to minimize the code to initialize the routes in the main file of the Node.js express application. We change the routes/index.js to have a constructor with a parameter: the express app itself

This is routes/index.js

/**
 * routes/index.js
 * All routes are here to import all of them just with one command
 * in the main app.js
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
var home = require('./home');
var guestbook = require('./guestbook');

module.exports = function (app) {
	home(app);
	guestbook(app);
}

See those calls to home and guestbook? we are passing again the express app instance to each route file, where we also change its shape to get that parameter. Be careful! now we have to specify the complete route to '/guestbook/', something that in fact makes everything much more clear

/**
 * routes/guestbook.js
 * The router for guestbook operations.
 * Keep in mind that here '/' refers to '/guestbook/'
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
var mongoose = require('mongoose');
var GuestBook = mongoose.model('GuestBook');

module.exports = function (app) {

    /**
    * get
    * GETs all guestbook data.
    */
    app.get('/guestbook/', function(req, res) {
    ...
}

home.js does the same

/**
 * routes/home.js
 * The home page, just renders the jade template
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
module.exports = function (app) {

	app.get('/', function(req, res) {
	    res.render('index.jade' , {title: 'Home page'});
	});

}

And now, this is how the main app.js looks like. Instead of using each route separately, now it's enough to do it once. In this example may seem a useless effort, but when your app evolves to have many different routes dispersed in many files we will add all of them with just one command, keeping our main app.js nice and clean.

/**
* app.js
* Main entrypoint for the app
* https://github.com/pello-io/simple-express-mongoose
* Pello Altadill - http://pello.info
*/
var express = require('express');
var bodyParser = require('body-parser');

var models = require('./models');
var routes = require('./routes');
var middleware = require('./middleware');

var app = express();

// If we want to use post data:
app.use(bodyParser());

// We set middlewares
middleware(app);

// We set all the routes with one single call
routes(app);

// We set static content
app.use(express.static('public'));

// And there we go, listening on port 3000
app.listen(3000, function () {
    console.log('now listening on http://localhost:3000');
});
Creating custom middleware

If you are using connect or express then it's probably making use of more than one middleware. In a nutshell, the middleware is some code that is executed between the request and te response in a Node.js web application. Therefore, whenever you call app.use(whatever) you are already applying middleware like routes, bodyParser, etc...

Some dummy middlewares

Let's create some middleware for testing. The first will just log the requests made to our server and the second will log a message. The second its useful only to observe the way the middlewares are chained for each request. As we can have more than one custom middleware and following the same style of the routes and models, we'll create a folder called middleware with an index.js file that will load and apply all the middlewares.

This is how the logrequest middleware looks like. Don't forget the next() call, or the request will not go on to next middleware!!!

/**
* logrequest
* this just logs every request to console
*/

module.exports = function logRequest (req, res, next) {
  console.log('request received: ');
  console.log("["+req.method+"] " + req.url);
  console.log(req.body);
  // and go on... if you don't call next the request will hang
  next();
}

And this is the dummy middleware

/**
* dummyddleware.js
* A dummy middleware just to see the order it is being called
*/

module.exports = function dummyddleware (req,res, next) {
	console.log('Dummy middleware');
	next();
}

And the index.js that applies them both to the expres app

/**
 * middleware/index.js
 * All middleware are here to import all of them just with one command
 * in the main app.js
 * Note that maybe this is not always desirable if you want to apply
 * any other middleware in a different order into app.js file.
 * @greetz for any
 */
var logrequest = require('./logrequest');
var dummyddleware = require('./dummyddleware');

module.exports = function (app) {
	app.use(logrequest);
	app.use(dummyddleware);
}

Finally as we have seen before, in the main entry-point we can just add

var middleware = require('./middleware');
...
// We set middleware
middleware(app);

At the time of writing this I'm receiving very valuable feedback about how to organize your projects, even with fullstack app generators. Which one is the best? It's the usual devious question that comes from a sales manager or the like. It depends on the project nature, don't you think?

You can clone, download(at this point of development), copy-paste this project from git. Don't forget to get the required node modules to make it work!

]]> http://www.pello.info/index.php/blog/keeping-node-js-app-js-clean-custom-middleware-for-express
Node.js + express routes + mongoose, simple and separated http://www.pello.info/index.php/blog/node-js-express-routes-mongoose-simple-and-separated http://www.pello.info/index.php/blog/node-js-express-routes-mongoose-simple-and-separated 2014-07-23 23:45:40 pelloxabier http://www.pello.info/index.php/blog/node-js-express-routes-mongoose-simple-and-separated express simple-express-mongoose This creates a directory with that name and an app.js with this content:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

Let's simplify to leave only the routes:

var express = require('express');
var index = require('./routes');
var guestbook = require('./routes/guestbook');


var app = express();

app.use(express.static('public'));

app.use('/', index);
app.use('/guestbook', guestbook);

app.listen(3000, function () {
        console.log('Listening on port 3000');
})
Requiring all routes just once

Applications tend to grow and so we would have to require every route in the main entrypoint for express. Instead of that we can require just the routes/index.js

exports.home = require('./home');
exports.guestbook = require('./guestbook');

Now app.js has simplified route requires

var express = require('express');
var routes = require('./routes'); // This will require 'routes/index.js' !!

var app = express();

app.use(express.static('public'));

app.use('/', routes.home);
app.use('/guestbook', routes.guestbook);

app.listen(3000, function () {
        console.log('Listening on port 3000');
})

I've seen samples where all routes are added to express with just one line of code, but it wasn't working here for me.

Adding MongoDB support

Ok, now we want to show guestbook messages from a MongoDB database. As we are using mongoose, we must define a schema for each collection, and so we'll create a guestbook.js file in a models folder. Here we could try the same procedure used for routes. We create a models/index.js file which connects to MongoDB and exports all mongoose schemas. Here is models/index.js

/**
 * models/index.js
 * All models are here to import all of them just with one command
 * in the main app.js, and by the way we connect to MongoDB
 * Better to use an external config.. I know.
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blog');

// optionally:
//mongoose.set('debug', true);

exports.GuestBook = require('./guestbook');

And this is the schema definition for the guestbook collection, mongoose style. MongoDB is a schemaless database but this driver forces you to define a schema.

The routes

Routes are separated, one file for the home request, other file for guestbook requests, and so forth as the app grows. home.js is pretty straightforward: when we receive a get request, just render the index.jade

And this is the route for guestbook.js, with the get and the post. post saves data and then redirects to get case.

app.js, finally

Here you have. There are more modules to load to improve this sample app, but at least routes and models now are kept apart.

You can clone, download(at this point of development), copy-paste this project from git. Don't forget to get the required node modules to make it work!

]]> express simple-express-mongoose This creates a directory with that name and an app.js with this content:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

Let's simplify to leave only the routes:

var express = require('express');
var index = require('./routes');
var guestbook = require('./routes/guestbook');


var app = express();

app.use(express.static('public'));

app.use('/', index);
app.use('/guestbook', guestbook);

app.listen(3000, function () {
        console.log('Listening on port 3000');
})
Requiring all routes just once

Applications tend to grow and so we would have to require every route in the main entrypoint for express. Instead of that we can require just the routes/index.js

exports.home = require('./home');
exports.guestbook = require('./guestbook');

Now app.js has simplified route requires

var express = require('express');
var routes = require('./routes'); // This will require 'routes/index.js' !!

var app = express();

app.use(express.static('public'));

app.use('/', routes.home);
app.use('/guestbook', routes.guestbook);

app.listen(3000, function () {
        console.log('Listening on port 3000');
})

I've seen samples where all routes are added to express with just one line of code, but it wasn't working here for me.

Adding MongoDB support

Ok, now we want to show guestbook messages from a MongoDB database. As we are using mongoose, we must define a schema for each collection, and so we'll create a guestbook.js file in a models folder. Here we could try the same procedure used for routes. We create a models/index.js file which connects to MongoDB and exports all mongoose schemas. Here is models/index.js

/**
 * models/index.js
 * All models are here to import all of them just with one command
 * in the main app.js, and by the way we connect to MongoDB
 * Better to use an external config.. I know.
 * https://github.com/pello-io/simple-express-mongoose
 * Pello Altadill - http://pello.info
 */
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blog');

// optionally:
//mongoose.set('debug', true);

exports.GuestBook = require('./guestbook');

And this is the schema definition for the guestbook collection, mongoose style. MongoDB is a schemaless database but this driver forces you to define a schema.

The routes

Routes are separated, one file for the home request, other file for guestbook requests, and so forth as the app grows. home.js is pretty straightforward: when we receive a get request, just render the index.jade

And this is the route for guestbook.js, with the get and the post. post saves data and then redirects to get case.

app.js, finally

Here you have. There are more modules to load to improve this sample app, but at least routes and models now are kept apart.

You can clone, download(at this point of development), copy-paste this project from git. Don't forget to get the required node modules to make it work!

]]> http://www.pello.info/index.php/blog/node-js-express-routes-mongoose-simple-and-separated