giovedì 28 novembre 2013

Asyncronous function in Node.js

There are two kind of function in Node.js:
  • Asyncronous, non blocking function 
  • Syncronous, blocking function
The first type, receive a result throw a callback function:

test('x', function(err, data){
}); 

A common mistake that a node.js newbies developer commit is try to return a value from an asyncronous function. The right way to work with asyncronous function is follow example below:
// Method
function query (sQuery, callback){
     var query = connection.query(sQuery);
     query.on('result',function(row){
        callback(null, row);
     });
};

// Implementation
query("select * from test", function(err, result){
    console.log(err || result);
});
It's important to note that asyncronous functions don't return something explicitly (like return x ...), but they set output values through a callback function; in above example callback function sets err (to null) and output value (to row). There are some paradigms to implement asyncronous functions and this link shows some of these

npm and package.json

npm is official package manager for node.js.
It can be runs throw command line and manages dependencies for an application.
With npm we can install a node.js package hosted on a node.js repository.
In this post i explain a simple package.json file that i wrote to distribute a node.js module (https://github.com/sergioska/noodlejuice).

{

  "name": "noodlejuise",

  "description": "Mini toolkit for node.js",

  "author": "Sergio Sicari <sergiosicari[]gmail.com>",

  "dependencies": {

        "mysql": ">=2.0.0-alpha9",

        "socket.io": ">=0.9.16",

        "node-mysql": ">=0.3.4",

        "csv": ">=0.3.4"

  },

  "directories": {

          "lib": "./lib"

  },

  "repository": {

            "type": "git",

            "url": "git://github.com/sergioska/noodlejuice"

  },

  "engine": "node 0.11.7"

}
In dependencies section there are dependencies module required by own application; in this case mysql, socket.io, node-mysql, csv module.

In repository section there is a link of application repository.

In this way we can install this application only with this package.json file; in a directory that contains this file we run the following command:

npm install