SlideShare a Scribd company logo
NodeJS, CS y ExpressJS
Como programar solo en JavaScript
y no morir en el intento.
“es una plataforma construida sobre el
Javascript runtime de Chrome, con el fin de
construir aplicaciones de red rápidas y
escalables.”
Esencialmente
I/O
- http
- net(tcp)
- udp
- fs
- dns
- etc...
Muchos modulos
HTTP Server de ejemplo
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello Worldn');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
- single threaded
- todo I/O es no bloqueante
- muchos callbacks
- no bloquear el reactor
Event Loop
Require()
//mate.js
var mate = {
cuadrado: function(x) {
return x * x
},
cubo: function(x) {
return x * cuadrado(x);
}
};
module.exports = math;
//otro.js
var express = require('express')
var mate = require('./mate.js')
mate.cuadrado(2);
mate.cubo(2);
- Instalar modulos:
Node Package Manager
npm install express
- Manejar dependencias (definidas en package.json):
npm install
gem install sinatra
bundle install
- Congelar dependencias:
npm shrinkwrap Gemfile.lock
package.json
{
"name": "TicTacToeNODE",
"version": "1.0.0",
"description": "",
"main": "app.js",
"engines": {
"node": "~1.4.28"
},
"dependencies": {
"body-parser": "^1.10.1",
"express": "^4.10.7",
"express-session": "^1.10.0",
"mongodb": "^1.4.28"
},
"devDependencies": {
"coffee-script": "^1.8.0"
},
"author": "",
"license": "ISC"
}
Dato Curioso
rubyGems: 94,343 gems (desde 2003).
npm: 116,873 packages (desde 20011).
- lenguaje que compila a javascript.
- es directamente compatible con librerías.
javascript (y vice-versa).
- sintaxis bonita. :D
- tiene su propia consola para node.
numero = 15
numeros = [1, 2, 3]
nombres = [
'Santi'
'Miguel'
'Mati'
]
cuadrado = (x) ->
x * x
mate =
cuadrado: (x) ->
x * x
cubo: (x) ->
x * cuadrado x
if numero > 10
console.log "Un numero: #{numero}"
console.log("Un numero: #{numero}") if numero > 10
var numero = 15;
var numeros = [1, 2, 3];
var nombres = ['Santi',
'Miguel',
'Mati'];
var cuadrado = function(x) {
return x * x
};
var mate = {
cuadrado: function(x) {
return x * x
},
cubo: function(x) {
return x * cuadrado(x);
}
};
if (numero > 10) {
console.log("Un numero: " + numero);
};
Javascript Coffeescript
Clases
class WinConditionRow
constructor: (rowNumber) ->
@rowNumber = rowNumber
hasWon: (board, player) ->
board[@rowNumber].every (cell) ->
cell == player
winCondition = new WinConditionRow(1)
winCondition.hasWon(board, player)
class Persona
constructor: (nombre, apellido) ->
@nombre = nombre
@apellido = apellido
obtenerNombreCompleto: ->
"#{@nombre} #{@apellido}"
class Doctor extends Persona
obtenerNombreCompleto: ->
"Dr. #{super()}"
Listas y bucles
num for num in [1..10]
game.getId() for game in games when game.isFinished()
for game in games
do (game) ->
game.play player, 0, 0
console.log game.getBoard()
ExpressJS
- framework web similar a Sinatra.
- super minimalista y modular.
express = require 'express'
app = express()
app.get '/', (req, res) ->
res.send 'Hello World!'
app.listen 3000
get '/match_ups' do
currentPlayerId = session[:player_id]
{player_id: currentPlayerId,
match_ups_pending_id: getPendingMatchUpsFor(currentPlayerId),
match_ups_finished_id: getFinishedMatchUpsFor(currentPlayerId)
}.to_json
end
app.get '/match_ups', (req, res) ->
currentPlayerId = req.session.playerId
resJSON =
player_id: currentPlayerId
match_ups_pending_id: pendingMatchUpIdsBy currentPlayerId
match_ups_finished_id: finishedMatchUpIdsBy currentPlayerId
res.send resJSON
express
Sinatra
session = require 'express-session'
bodyParser = require 'body-parser'
app.use express.static("#{__dirname}/public")
app.use bodyParser.json()
app.use session(cookieConfig)
app.post '/play_match_up/:match_up_id', (req, res) ->
gameId = parseInt req.params.match_up_id
i = parseInt req.body.i
j = parseInt req.body.j
game = getGameById(gameId)
game.play req.session.playerId, i, j
res.sendStatus 200
Conclusiones

More Related Content

Node lt

  • 1. NodeJS, CS y ExpressJS Como programar solo en JavaScript y no morir en el intento.
  • 2. “es una plataforma construida sobre el Javascript runtime de Chrome, con el fin de construir aplicaciones de red rápidas y escalables.”
  • 4. - http - net(tcp) - udp - fs - dns - etc... Muchos modulos
  • 5. HTTP Server de ejemplo var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello Worldn'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/');
  • 6. - single threaded - todo I/O es no bloqueante - muchos callbacks - no bloquear el reactor Event Loop
  • 7. Require() //mate.js var mate = { cuadrado: function(x) { return x * x }, cubo: function(x) { return x * cuadrado(x); } }; module.exports = math; //otro.js var express = require('express') var mate = require('./mate.js') mate.cuadrado(2); mate.cubo(2);
  • 8. - Instalar modulos: Node Package Manager npm install express - Manejar dependencias (definidas en package.json): npm install gem install sinatra bundle install - Congelar dependencias: npm shrinkwrap Gemfile.lock
  • 9. package.json { "name": "TicTacToeNODE", "version": "1.0.0", "description": "", "main": "app.js", "engines": { "node": "~1.4.28" }, "dependencies": { "body-parser": "^1.10.1", "express": "^4.10.7", "express-session": "^1.10.0", "mongodb": "^1.4.28" }, "devDependencies": { "coffee-script": "^1.8.0" }, "author": "", "license": "ISC" }
  • 10. Dato Curioso rubyGems: 94,343 gems (desde 2003). npm: 116,873 packages (desde 20011).
  • 11. - lenguaje que compila a javascript. - es directamente compatible con librerías. javascript (y vice-versa). - sintaxis bonita. :D - tiene su propia consola para node.
  • 12. numero = 15 numeros = [1, 2, 3] nombres = [ 'Santi' 'Miguel' 'Mati' ] cuadrado = (x) -> x * x mate = cuadrado: (x) -> x * x cubo: (x) -> x * cuadrado x if numero > 10 console.log "Un numero: #{numero}" console.log("Un numero: #{numero}") if numero > 10 var numero = 15; var numeros = [1, 2, 3]; var nombres = ['Santi', 'Miguel', 'Mati']; var cuadrado = function(x) { return x * x }; var mate = { cuadrado: function(x) { return x * x }, cubo: function(x) { return x * cuadrado(x); } }; if (numero > 10) { console.log("Un numero: " + numero); }; Javascript Coffeescript
  • 13. Clases class WinConditionRow constructor: (rowNumber) -> @rowNumber = rowNumber hasWon: (board, player) -> board[@rowNumber].every (cell) -> cell == player winCondition = new WinConditionRow(1) winCondition.hasWon(board, player) class Persona constructor: (nombre, apellido) -> @nombre = nombre @apellido = apellido obtenerNombreCompleto: -> "#{@nombre} #{@apellido}" class Doctor extends Persona obtenerNombreCompleto: -> "Dr. #{super()}"
  • 14. Listas y bucles num for num in [1..10] game.getId() for game in games when game.isFinished() for game in games do (game) -> game.play player, 0, 0 console.log game.getBoard()
  • 15. ExpressJS - framework web similar a Sinatra. - super minimalista y modular. express = require 'express' app = express() app.get '/', (req, res) -> res.send 'Hello World!' app.listen 3000
  • 16. get '/match_ups' do currentPlayerId = session[:player_id] {player_id: currentPlayerId, match_ups_pending_id: getPendingMatchUpsFor(currentPlayerId), match_ups_finished_id: getFinishedMatchUpsFor(currentPlayerId) }.to_json end app.get '/match_ups', (req, res) -> currentPlayerId = req.session.playerId resJSON = player_id: currentPlayerId match_ups_pending_id: pendingMatchUpIdsBy currentPlayerId match_ups_finished_id: finishedMatchUpIdsBy currentPlayerId res.send resJSON express Sinatra
  • 17. session = require 'express-session' bodyParser = require 'body-parser' app.use express.static("#{__dirname}/public") app.use bodyParser.json() app.use session(cookieConfig) app.post '/play_match_up/:match_up_id', (req, res) -> gameId = parseInt req.params.match_up_id i = parseInt req.body.i j = parseInt req.body.j game = getGameById(gameId) game.play req.session.playerId, i, j res.sendStatus 200