jueves, 19 de julio de 2012

Decimal to Binary on Node.JS

Since I joined SAP Labs, I had to learn more programming languages and technologies. One of those is Node.JS or Node for the friends...

I have been studying it for a couple of days, because I was on vacations for a week, and as I always do with any new programming language I learn, I build a Decimal to Binary application -:)

I gotta say...I'm not a big fan on JavaScript...I have use it only a few times and I avoid it every time I can, but Node is starting to change my points of view. Node is really awesome as it allows us to create our own web server and hence control the flow as we want it. Really nice...

To make my life easier, I installed Express which is a Node Web Framework.

I create a file called app.js and a folder called views where I put a file called index.ejb

app.js
var express = require('express')

var app = express.createServer()
app.listen(8000)

function toBinary(Decimal){
 var bnum = 0, bexp = 1, digit = 0, bsum = 0;
 while(Decimal > 0){
  digit = Decimal % 2;
  Decimal = Math.floor(Decimal / 2);
  bsum = bsum + digit * bexp;
  bexp = bexp * 10;
 }
 return(bsum);
}

app.configure(function(){
  app.set('views', __dirname + '/views');
});

app.get('/', function(req, res) {
 res.render('index.ejs', {})
})

app.post('/send', express.bodyParser(), function(req, res) {
 if (req.body && req.body.Decimal) {
  var Binary = toBinary(req.body.Decimal)
  res.send("The Binary number is: " + Binary)
 } else {
  res.send("Please enter a Decimal number")
 }
})

app.get('/tweets', function(req,res) {
 res.send(tweets)
})


index.ejb
<h3>Node.JS - Decimal to Binary</h3>
<form action="/send" method="POST">
Decimal number: <input length="10" name="Decimal" type="text" />
<input type="submit" value="To Binary" />
</form>
Now, some screenshots...


For sure...I still got a long way of Node learning...so I hope to post more pretty soon...

Greetings,

Blag.


No hay comentarios: