miércoles, 21 de marzo de 2012

[en] Twitter Notify Me - Desktop notifications for twitter

Digging about another project that requires sending messages via D-Bus I decided to make this simple app, that shows a notification of my recent tweets (your) timeline , and with this I can be updated about what's going on twitter while you do your daily tasks ...

It was originally made​only for Linux environments, because in my work I have ubuntu, but then with the help of @dual3nigma decided port to mac and window$ using growl.

The app requires the libnotify library for Linux environments and growl for Mac / Window$, was made with Node.js and the code is available at Github where you will find all the steps to install and use.

Twitter Notify Me - Desktop notifications for twitter


Indagando sobre otro proyecto que requiere envio de mensajes a través de D-Bus se me ocurrió hacer esta simple app, que me mustra en un cuadro de notificación los últimos tweets de mi (tu) timeline, y con esto poder estar actualizado de lo que pasa en twitter al mismo tiempo que haces tus tareas diarias...

En un principio fue realizada sólo para entornos linux, ya que en mi trabajo tengo ubuntu, pero luego con la ayuda de @dual3nigma decidí portalo a mac y window$ utilizando growl.

La app require de la librería libnotify en entornos linux y de growl para Mac / Window$, fue realizada con Node.js y el código está disponible en Github en donde encontrará todos los pasos para instalarla y usarla.

jueves, 15 de marzo de 2012

#02 Manejo de rutas con Express framework



Este es el segundo post de la serie sobre node.js (socket.IO y mongoDB), si no lo hicieron lean el primero post #1.

Este capitulo es sobre el manejo de rutas, como ya sabrán cuando creamos nuestro servidor (en nuestro caso usando express) debemos declarar las rutas que manejaremos, y si bien esto a primera vista parece fácil hay algunas cosas a tener en cuenta.



Comencemos con algo simple, establecer la respuesta para la ruta "/"


app.get('/',function(req,res){
 res.write('handler : / \n');
 res.end();
});


Con lo anterior establecemos como manejaremos un requerimiento de nuestro index (ej: http://javierviola.blogspot.com) y que para este post en particular responderemos simplemente con el texto handler : /.


Antes de seguir una aclaración, para demostrar el uso de rutas utilice simplemente los métodos res.write y res.end con el fin de imprimir la función que respondió el requerimiento y los parámetros pasados.


Habiendo dicho eso, sigamos...

Probamos la ruta /

lucaMac:02-Routes pepo$ curl localhost:3000
handler : / 

lucaMac:02-Routes pepo$ curl localhost:3000/
handler : / 
Vemos que responde a los dos requerimientos, ya que express se encarga de esa última barra (/) por nosotros.

Ahora imaginemos que nuestra aplicación maneja usuarios, por lo que definimos lo siguiente:

app.get('/users/:id?',function(req,res){
 res.write('handler: /users/:id? \n');
 res.write('parametros: \n');
 for(key in req.params){
  res.write('\t'+key+' : '+req.params[key]);
 }
 res.write('\n');
 res.end(); 
});


Esto nos permitiría responder tanto a un GET de /users como a /users/12 o /users/pedro, y esto es posible porque el primer parámetro de la funci&oacuet;n get express lo utiliza como una expresión regular, por lo cual esta definición puede servir para lista todos los usuarios, algun usuario o los usuarios que matcheen con el valor de :id.

Y esto es posible porque :id define un placeholder lo cual nos permite acceder al valor a través del objeto req.params.

Veamos las diferentes respuestas:

lucaMac:02-Routes pepo$ curl localhost:3000/users
 handler: /users/:id? 
 parametros: 
  id : undefined
 lucaMac:02-Routes pepo$ curl localhost:3000/users/pedro
 handler: /users/:id? 
 parametros: 
  id : pedro
 lucaMac:02-Routes pepo$ curl localhost:3000/users/25
 handler: /users/:id? 
 parametros: 
  id : 25

También podemos definir varios placeholders simplemente cambiando el primer argumento:

app.get('/users/:id/:action',function(req,res){
   res.write('handler: /users/:id \n');
   res.write('parametros: \n');
   for(key in req.params){
    res.write('\t'+key+' : '+req.params[key]+'\n');
   }
  res.end(); 
  });
 
Lo cual nos permite acceder a los parámetros id y action.

Y si bien esto es muy útil, podemos hacer cosas más complejas gracias a las regex como por ejemplo:

app.get('/users/:id([0-9]+)/:action(edit|delete|create)',function(req,res){
  res.write('handler: /users/:id \n');
  res.write('parametros: \n');
  for(key in req.params){
   res.write('\t'+key+' : '+req.params[key]+'\n');
  }
  res.end(); 
 });
  
Y como pueden observar, aquí no sólo accedemos a id y action, sino que restringimos el primero a que sea numérico y damos tres opciones para el segundo, gracias a las regex :)

Veamos como funciona:
curl localhost:3000/users/25/edit
 handler: /users/:id 
 parametros: 
  id : 25
  action : edit
 lucaMac:02-Routes pepo$ curl localhost:3000/users/25/delete
 handler: /users/:id 
 parametros: 
  id : 25
  action : delete
 lucaMac:02-Routes pepo$ curl localhost:3000/users/25/del
 Cannot GET /users/25/del
 lucaMac:02-Routes pepo$ curl localhost:3000/users/pedro/delete
 Cannot GET /users/pedro/delete
Como vemos funciona y si la regex no se cumple 404 no se puede encontrar....
lucaMac:02-Routes pepo$ curl localhost:3000/users/pedro/delete -I
 HTTP/1.1 404 Not Found
 X-Powered-By: Express
 Content-Type: text/plain
 Connection: keep-alive

* Ya veremos al final una posibilidad de manejar esto de una forma más pro




Bueno ya manejamos los GETs ahora queremos manejar los POSTs para ello definimos:


app.post('/users',function(req,res){
 res.write('handler post: /users/ \n');
 res.write('parametros en body: \n');
 for(key in req.body){
  res.write('\t'+key+' : '+req.body[key]+'\n');
 }
 res.end(); 
});
Y en este caso nos valemos del middleware bodyParser que nos permite acceder a los valores pasados a través del objeto req.body.

Una cosa interesante de express es que nos ofrece el middleware methodOverride que nos permite ser más semántico en nustras rutas, ya que no permite que un POST sea transformado en un PUT o y así ser manejado por app.put o app.delete respectivamente...

Para ello veamos la siguiente definición:

/* post */
 app.post('/users',function(req,res){
  res.write('handler post: /users/ \n');
  res.write('parametros en body: \n');
  for(key in req.body){
   res.write('\t'+key+' : '+req.body[key]+'\n');
  }
  res.end(); 
 });

 /* We can use put to be more semantics, like a RESTful api.
   For this be use the middleware methodOverride, this 
   middleware check for the input _method in the body
   (this input could be hidden for don't show to the 
   end user), and if its present tranform the post in the 
   _method input value and don't pass this in req.body
  */
 app.put('/users',function(req,res){
  res.write('handler put: /users/ \n');
  res.write('parametros en body: \n');
  for(key in req.body){
   res.write('\t'+key+' : '+req.body[key]+'\n');
  }
  res.end(); 
 });

 /* delete, as in put we can use methodOverride to be
    more semantic 
 */
 app.delete('/users',function(req,res){
  res.write('handler delete: /users/ \n');
  res.write('parametros en body: \n');
  for(key in req.body){
   res.write('\t'+key+' : '+req.body[key]+'\n');
  }
  res.end(); 
 });
 
Como vemos definimos la misma ruta para los tres verbos http (POST,PUT,DELETE), y gracias al middleware methodOverride atender cada uno de ellos según el valor del input _method que se pase, y para explicarlo mejor un ejemplo:

Un post común:

lucaMac:02-Routes pepo$ curl -X POST -d "id=32&action=delete" localhost:3000/users/
 handler post: /users/ 
 parametros en body: 
  id : 32
  action : delete
 
Un post, pero que será respondido como put:

lucaMac:02-Routes pepo$ curl -X POST -d "id=32&action=delete&_method=put" localhost:3000/users/
 handler put: /users/ 
 parametros en body: 
  id : 32
  action : delete
 
vean como se pasa el valor de _method para que el middleware sobreescriba el método

Y por último el mismo post, pero respondido como delete
lucaMac:02-Routes pepo$ curl -X POST -d "id=32&action=delete&_method=delete" localhost:3000/users/
 handler delete: /users/ 
 parametros en body: 
  id : 32
  action : delete 
Y con esto queda explicado el middleware...

Una cosa importante a tener en cuenta es que las rutas se procesan secuencialmente y en la ubicación que fueron declaradas, es por eso que es muy importante hacer una declaración ordenada de nuestras rutas para que cada requerimiento sea atendido por la ruta que queramos y no por otra


Y haciendo uso de esto último, y utilizando un wildcard podemos manejar los errores 404 de una forma simple con esta ruta al final de todo:

app.all('*',function(req,res){
  res.write('handler all: *\n');
  res.write('ERR, no regex match\n');
  res.end();
 });
 
De esta forma atenderemos cualquier ruta (*) y en cualquier verbo http que no haya sido manejada anteriormente, con lo cual es muy útil para servir errores 404

Veamos como funciona:

lucaMac:02-Routes pepo$ curl -X POST -d "id=32&action=delete" localhost:3000/users/dasdsdas
 handler all: *
 ERR, no regex match
 lucaMac:02-Routes pepo$ curl -X GET -d "id=32&action=delete" localhost:3000/usedasd
 handler all: *
 ERR, no regex match
 

Espero que haya sido claro en como es el uso de rutas con express y cualquier cosa no duden en contactarme
Les dejo el código utilizado Código en Github

Hasta la próxima (con la explicación de como funcionan los middlewares :) )


viernes, 9 de marzo de 2012

[en] #01 Express framework basic config



This series of posts, are related to the previous post node.js apps with real time which explains how to install the necessary components to develop an application with node.js + socket.IO + MongoDB.
But along the way I thought best to start with some basics, and from them be adding complexity until an application (I have not yet defined, hearing ideas...) which makes use of socket.IO for real-time interactions.

Well, let's start with a very basic introduction to Express frameworks.
This framework is widely used and perfectly combines with socket.IO, is very simple to use and brings many things "out of the box" ready to use.

The first thing we do is create the environment where we will develop this demo, we created the directory for this application and within the structure we create the following subdirectories:
pepo@frank3:~$ mkdir 01-basic_express && cd 01-basic_express
pepo@frank3:~$ mkdir views
pepo@frank3:~$ mkdir node_modules
pepo@frank3:~$ mkdir -p public/img
pepo@frank3:~$ mkdir -p public/css
pepo@frank3:~$ mkdir -p public/js
I will explain each directory use:
views : The directory where our templates lives
node_modules : Where were installed modules it will use
public : Content css, js, imagenes,etc.

once created the directories, open our favorite editor to start developing our app.
The content of this simple example is:
/**
* Module dependencies.
*/

var express = require('express');
var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false                 
});   
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

// Routes

app.get('/',function(req,res){
res.render("index",{
title: "01 - basic express ",                         
banner: "Hello from template!"                        
});                                 
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Now we are going to analyze these lines:
var express = require('express');
var app = module.exports = express.createServer();
In these two lines load the module you need and call the function createServer we return an object with the web server will use to listen to requests and answer them.

Then we go to its configuration, which are the following lines
// Configuration

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false                 
});   
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
They first set the directory / views as a repository of templates, for this we use a variable defined globally node.js runtime is __dirname whose value is a string with the absolute path of the directory of your app.
Then we set to "ejs" as our engine for rendering templates, so remember to install the module via npm (npm install ejs).
The final set is to establish that we will not use a layout file for this example, if we wanted we could have a database file for all of our templates or for use only for some pages.
Then we declare the Middlewares we will use the first express.bodyParser () is used for parsing of the post (either json or not) and you return the result parses the variable accessible via req.body , the following is express.methodOverride () that is important to be declared after express.bodyParser () because it performs a check on the variable req.body , this middleware is useful to override the methods of our forms, just an input field with the hidden attribute, like this:
<form action="/" method="post">
<input name="_method" type="hidden" value="put" />
<input name="user[name]" type="text" />
<input type="submit" value="Submit" />
&nbsp;&nbsp;&nbsp; </form>
That will allow us to access the post as follows:
app.put('/', function(){
console.log(req.body.user);    
});
Then we declare the use of app.router which is simply the middleware that contains all the paths defined, and performs route lookup based on the URL of the current request and the HTTP method.
And finally declare the directory from where we provide our static content express.static (__dirname + '/ public') , this allows us to access our resources (in the directory public ) directly referencing it as , note that there is no need to reference the directory public but directly we refer to directories in there

Well, with this we have our first app using node & Express, the code in this first post is on Github Posts


Until next time!

jueves, 8 de marzo de 2012

[en] GitHub hacked... so we have to audit SSH keys


lucaMac:nodeapps pepo$ git clone git@github.com:pepoviola/Socket.IO_rooms.git
Cloning into Socket.IO_rooms...
ERROR: Hi pepoviola, it's GitHub. We're doing an SSH key audit.
Please visit https://github.com/settings/ssh/audit/1767330
to approve this key so we know it's safe.
Fingerprint: 7c:(...):54
fatal: The remote end hung up unexpectedly

Yes, I had read the news that they had exploited a vulnerability that allowed update rails attributes inserting a new SSH key for more detail can read these links [0].

Therefore began an audit GitHub SSH key, for it asks that we enter the link listed above ("Please visit https://github.com/settings/ssh/audit/1767330") to approve or reject our key now ... If you have multiple keys as I uploaded to github, since different machines rub shoulders and this means that you must enter each machine and check if the ssh fingerprint is correct or not. Which brings us to what inspired me to write this post, i dont know if everyone knows how to read your fingerprint to validate the github presented to us, if do not know it I leave here a simple explanation.

The first thing to know is where is our public key, which usually is in the path ~/.ssh/ (/home/[user]/.ssh) with the name id_rsa.pub, when you have found this file must run the following command
ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 7c: (...): 54 /Users/pepo/.ssh/id_rsa.pub (RSA)
Which we will return three fields, the first is the size, the second is our fingerprint and is ultimately the public key file.


I hope it was useful and approved yours ssh key on github : D

Links
[0]
     homakov commit (very funny comments)
     how to Gist explaining how the vulnerability was exploited
      thehackernews

GitHub hacked... asique vamos a auditar claves SSH


lucaMac:nodeapps pepo$ git clone git@github.com:pepoviola/Socket.IO_rooms.git
Cloning into Socket.IO_rooms...
ERROR: Hi pepoviola, it's GitHub. We're doing an SSH key audit.
Please visit https://github.com/settings/ssh/audit/1767330
to approve this key so we know it's safe.
Fingerprint: 7c:(...):54
fatal: The remote end hung up unexpectedly

Así es, había leido de la noticia de que habían explotado una vulnerabilidad de rails que permitía updetear los atributos insertando una nueva key de SSH, para más detalle puede leer estos links [0].

Por lo tanto Github comenzó una auditoria de claves SSH, para  ello nos pide que ingresemos al link que figura arriba (" Please visit https://github.com/settings/ssh/audit/1767330 "), para aprobar o rejectar nuestras claves, ahora... Si tu tienen como yo varias claves subidas a github, ya que codeas e diferentes maquinas esto representa que debes ingresar a cada maquina y chequear si el fingerprint de ssh es correcto o no. Lo cual nos trae a lo que me inspiró a escribir este post, que es que no sé si todo el mundo sabe como leer su fingerprint para validarlo con los que nos presenta github, si no lo saben les dejo aquí una simple explicación.

Lo primero que debemos saber es donde se encuentra nuestra llave pública, que por lo general se encuentra en el path ~/.ssh/ (/home/[user]/.ssh) con el nombre id_rsa.pub, una vez localizado este archivo debemos ejecutar el siguiente comando
ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 7c:(...):54 /Users/pepo/.ssh/id_rsa.pub (RSA)
El cual nos devolverá tres campos, el primero es el tamaño, el segundo es nuestro fingerprint y por último es archivo de la clave pública.

Buenos, espero que les haya servido y a aprobar claves ssh en github :D





Links
[0]
     homakov commit (Muy divertidos los comentarios)
     how to Gist que explica como se explotó la vulnerabilidad
     noticia en thehackernews

martes, 6 de marzo de 2012

#01 Uso básico de Express framework



Esta serie de post, tienen relación con el post anterior real time apps con node.js el cual explica como realizar la instalación de los componentes necesarios para desarrollar una aplicación con node.js + mongoDB + socket.IO.
Pero en el camino me pareció mejor comenzar con algunas cosas básicas, y a partir de ellas ir sumando complejidad hasta lograr una aplicación (que todavía no tengo definida cual sera, se escuchan ideas) que haga uso de socket.IO para las interacciones en tiempo real.

Bueno, vamos a comenzar con una introducción muy básica a frameworks Express.
Este framework es muy utilizado y se combina a la perfección con socket.IO, es muy simple de utilizar y trae muchas cosas "out of the box" lista para utlizar.

Lo primero que vamos a hacer es crear el entorno donde desarrollaremos este demo, para ello creamos el directorio de la aplicación y dentro de el creamos la siguiente estructura de subdirectorios:

pepo@frank3:~$ mkdir 01-basic_express && cd 01-basic_express
pepo@frank3:~$ mkdir views
pepo@frank3:~$ mkdir node_modules
pepo@frank3:~$ mkdir -p public/img
pepo@frank3:~$ mkdir -p public/css
pepo@frank3:~$ mkdir -p public/js

Paso a explicar para que utilizares cada directorio:

views : Es el directorio donde alojaremos nuestros templates
node_modules : Donde se instalaran los módules que utilizaremos
public : Directorio de contenido, aquí alojaremos nuestros css, js, imagenes, etc.

Una vez creados los directorios, abrimos nuestro editor preferido para comenzar a desarrollar nuestra app.
El contenido de este simple ejemplo es:
/**
* Module dependencies.
*/

var express = require('express');
var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false                 
});   
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

// Routes

app.get('/',function(req,res){
res.render("index",{
title: "01 - basic express ",                         
banner: "Hello from template!"                        
});                                 
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Ahora vamos a ir analizando estas líneas:

var express = require('express');
var app = module.exports = express.createServer();
En estas dos líneas cargamos el módulo que necesitamos y llamamos a la función createServer que nos retorna un objeto con el servidor web que utilizaremos para escuchar las peticiones y responderlas.

Luego pasamos a la configuración del mismo, que son las siguientes líneas
// Configuration

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false                 
});   
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
En ellas primero establecemos el directorio /views como repositorio de templates, para ello usamos una variable definida globalmente en tiempo de ejecució de node.js que es __dirname cuyo valor es un string con el path absoluto del directorio de nuestra app.
Luego establecemos a "ejs" como nuestro motor para renderizar los templates, para ello recordemos intalar el módulo vía npm (npm install ejs).
El último set es para establecer que no utilizaremos un archivo de layout para este ejemplo, si quiesieramos podríamos tener un archivo de base para todos nuestros templates o también para utilizar sólo para algunas páginas.

Luego declaramos los Middlewares que vamos a utilizar, el primero express.bodyParser() es utilizado para el parseo de los post (sean json o no) y nos devuelve el resultado del parsea accesible vía la variable req.body , el siguiente es express.methodOverride() que es importante que esté declarado después de express.bodyParser() ya que realiza una verificación sobre la variable req.body , este middleware es muy útil para sobreescribir los métodos de nuestros formularios, simplemente con un campo input con el atributo hidden, algo así:
<form action="/" method="post">
<input name="_method" type="hidden" value="put" />
<input name="user[name]" type="text" />
<input type="submit" value="Submit" />
&nbsp;&nbsp;&nbsp; </form>
Que nos permitirá acceder al post de la siguiente forma:
app.put('/', function(){
console.log(req.body.user);    
});

Luego declaramos el uso de app.router que es simplemente el middleware que contiene todas las rutas definidas, y realiza consulta de rutas basándose en la URL de la solicitud actual y el método HTTP.
Y por último declaramos el directorio desde donde proveemos nuestro contenido estático express.static(__dirname + '/public'), esto nos permite acceder a nustros recursos (dentro del directorio public) directamente referenciandolo como <link href="/css/style.css" rel="stylesheet" type="text/css"></link> , noten que no hace falta referenciar el directorio public sino que directamente hacemos referencia a los directorios dentro del mismo.

Bueno y con esto tenemos nuestra primera app utilizando node & Express, el código de este primer post se encuentra en Github Posts

Hasta la próxima!

domingo, 4 de marzo de 2012

[ en ] Working with node.js and MySQL




This is a small article about how to use node.js as web server to display the results of a query to a MySQL database engine.
The first thing to do is to check is that we have installed the mysql module to run it the following:

lucaMac:BLOG_POSTs pepo$ node
> var Client = require('mysql').Client
Error: Cannot find module 'mysql'
at Function._resolveFilename (module.js:332:11)
at Function._load (module.js:279:25)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at repl:1:14
at REPLServer.eval (repl.js:80:21)
at repl.js:190:20
at REPLServer.eval (repl.js:87:5)
at Interface. (repl.js:182:12)
at Interface.emit (events.js:67:17)
> 
If fails, proceed to install the module via npm:

npm install mysql



The first thing we do is create the object for the query:

var Client = require('mysql').Client,
client = new Client();
client.user = 'user';
client.password = 'password';
client.host='127.0.0.1';
client.port='3306';
client.database='database_name'
client.connect();

then create the web server


var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});

And within this we perform the query, and associate to its callback function

client.query(
"select * from table where campo1 > 1 limit 10;",    
function select(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
print data to the console and the web response


console.log("Number of rows: "+results.length);
console.log(results);


for (var i in results){

var result = results[i];
res.write(result.campo1+"\n");
}

res.end();
});
We finished the code, setting up a port for listening

}).listen(1337, "0.0.0.0");
console.log('Server running ');


The finished script is like this:

var Client = require('mysql').Client,
client = new Client();
client.user = 'user';
client.password = 'password';
client.host='127.0.0.1';
client.port='3306';
client.database='DB'
client.connect();


var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});


client.query(
"select * from table where campo1 > 1 limit 10;",    
function select(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
console.log("Number of rows: "+results.length);
console.log(results);
res.write(results);

for (var i in results){

var result = results[i];
res.write(result.campo1+"\n");
}
res.end();
});

}).listen(1337, "0.0.0.0");
console.log('Server running ');
If you want to download this is the link to the   gist

jueves, 1 de marzo de 2012

[en] node.js + socket.IO + mongoDB = real time apps Part 1




Part 1: Setting the environment ....

A few days ago I finished a simple application tweetland.com.ar I made in order to learn more about Node.js and MongoDB ... on the road I also came across Socket.IO which is a great library for real time applications.
The first is to prepare the environment. To do this first download node.js (from node.js ), after downloading the installation follows the traditional steps:
./configure
make
make install *
* the last step as root Once installed, continue with the installation of modules. For this node has npm (which is Node Package Manager) that allows us to install the modules with a single command install npm . Instructions for installing npm are in your home page, also I leave
curl http://npmjs.org/install.sh | sh
At this time we have installed both node.js as its package manager npm. Usually what I usually do is create a directory in my case I call nodeapps as workspace.
Entering the same:
cd "path to nodeapps"
and within it begin to install the modules you require. This is important because when you install the modules npm node_modules create the directory (if not there before), and install the modules in that directory.
This is important because when we do within our code something like:
var sys = require('sys');
node will automatically search the directory sys module within node_modules in the current directory and not finding it will continue with the search recursively upwards, which is always important to remember where you installed the modules that we use.

Before going further make the installation of some modules used, these are express, socket.io, mongoose.

And this is precisely the last module we will use to interact with our database MongoDB, which is an object-oriented database (JSON), high performance and scalable. (in another post I will explain a little more how it works because it is a relatively new and very interesting).
To install you have to download the appropriate version from download , and once discharged, proceed to decompress

 pepo@sokol:~/DESARROLLO/POSTS/node_socket_mongo$ wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-2.0.2.tgz

2012-02-28 11:42:19 (1.06 MB/s) - `mongodb-linux-i686-2.0.2.tgz' saved [38157227/38157227]

pepo@sokol:~/DESARROLLO/POSTS/node_socket_mongo$ tar -xzf mongodb-linux-i686-2.0.2.tgz
Once unpacked and could start the service mongod and start, but I'd rather create the directory structure I will use my base, create two directories for data and logs, the first store the files of the database and the second of logs. I also create the configuration file with which I will start the service, in my case is as follows:
cat mongod.config 

dbpath = /home/pepo/nodeapps/data/
logpath =/home/pepo/nodeapps/logs/mongodb.log
bind_ip = 127.0.0.1
noauth = true 
verbose = true 
 Bind_ip option is set to only listen on localhost requests (since by default it does on all interfaces) and indicate that we will not configure the authentication and verbose.

To start the service simply run:
bin/mongod --config mongod.config *
* Inside the unzipped directory MongoDB

we see something like this:
 # mongodb-linux-i686-2.0.2/bin/mongod --config mongod.config 
all output going to: ./logs/mongodb.log
Finally to test the service entered as follows (always from the binary directory MongoDB):
pepo@sokol:bin$ ./mongo
MongoDB shell version: 2.0.2
connecting to: test
> show dbs
local    (empty)
Well, with this we have our environment set up and configured to start programming applications in node.js with MongoDB, but that will be for the next post....