Beruflich Dokumente
Kultur Dokumente
js
12/10/2014
El Libro para
Principiantes en Node.js
Un tutorial de Node.js por: Manuel Kiessling & Herman A.
Junge
Sobre el Tutorial
El objetivo de este documento es ayudarte a empezar con el
desarrollo de aplicaciones para Node.js, ensendote todo lo
que necesites saber acerca de JavaScript "avanzado" sobre la
marcha. Este tutorial va mucho ms all del tpico manual
"Hola Mundo".
Status
Ests leyendo la versin final de este libro, es decir, las
actualizaciones solo sern hechas para corregir errores o para
reflejar cambiar en nuevas versiones de Node.js.
Las muestras de cdigo de este libro estn probadas para
funcionar con la versin 0.6.11 de Node.js.
Audiencia Objetivo
Este documento probablemente ser mejor entendido por los
lectores que tengan un trasfondo similar al mo: Programadores
experimentados en al menos un lenguaje orientado al objeto,
como Ruby, Python, PHP o Java; poca experiencia con
JavaScript, y ninguna experiencia en Node.js.
El que este documento est orientado a desarrolladores que ya
tienen experiencia con otros lenguajes de programacin
http://www.nodebeginner.org/index-es.html
1 / 52
12/10/2014
2 / 52
12/10/2014
Tabla de Contenidos
JavaScript y Node.js
JavaScript y T
Antes que hablemos de toda la parte tcnica, tommonos un
minuto y hablemos acerca de ti y tu relacin con JavaScript.
Este captulo est aqu para permitirte estimar si tiene sentido
el que sigas o no leyendo este documento.
Si eres como yo, empezaste con el "desarrollo" HTML hace
bastante tiempo, escribiendo documentos HTML. Te
encontraste en el camino con esta cosa simptica llamada
JavaScript, pero solo la usabas en una forma muy bsica,
agregando interactividad a tus pginas de cuando en cuando.
Lo que realmente quisiste era "la cosa real", Queras saber
cmo construir sitios web complejos - Aprendiste un lenguaje
de programacin como PHP, Ruby, Java, y empezaste a escribir
cdigo "backend".
No obstante, mantuviste un ojo en JavaScript, y te diste cuenta
que con la introduccin de jQuery, Prototype y otros, las cosas
se fueron poniendo ms avanzadas en las Tierras de JavaScript,
http://www.nodebeginner.org/index-es.html
3 / 52
12/10/2014
4 / 52
12/10/2014
es una gua.
Mi objetivo es proveerte esta gua.
Una Advertencia
Hay algunas personas realmente excelente en JavaScript. No
soy una de ellas.
Yo soy realmente el tipo del que te he hablado en los prrafos
previos. S un par de cosas acerca de desarrollar aplicaciones
backend, pero an soy nuevo al JavaScript "real" y an ms
nuevo a Node.js. He aprendido solo recientemente alguno de
los aspectos avanzados de JavaScript. No soy experimentado.
Por lo que este no es un libro "desde novicio hasta experto".
Este es ms bien un libro "desde novicio a novicio avanzado".
Si no fallo, entonces este ser el tipo de documento que deseo
hubiese tenido cuando empec con Node.js.
5 / 52
12/10/2014
"Hola Mundo"
Ok. Saltemos entonces al agua fra y escribamos nuestra
primera aplicacin Node.js: "Hola Mundo".
Abre tu editor favorito y crea un archivo llamado holamundo.js.
Nosotros queremos escribir "Hola Mundo" a STDOUT, y aqu
est el cdigo necesario para hacer esto:
console.log("Hola Mundo");
6 / 52
12/10/2014
La Pila de Aplicaciones
http://www.nodebeginner.org/index-es.html
7 / 52
12/10/2014
8 / 52
12/10/2014
Bueno, con Node.js, las cosas son un poco distintas. Porque con
Node.js, no solo implementamos nuestra aplicacin, nosotros
tambin implementamos todo el servidor HTTP completo. De
hecho, nuestra aplicacin web y su servidor web son
bsicamente lo mismo.
Esto puede sonar como mucho trabajo, pero veremos en un
momento que con Node.js, no lo es.
Empecemos por el principio e implementemos la primera parte
de nuestra pila, el servidor HTTP..
Construyendo la Pila de
Aplicaciones
Un Servidor HTTP Bsico
Cuando llegu al punto donde quera empezar con mi primera
aplicacin Node.js "real", me pregunt no solo como la iba a
programar, sino que tambin, como organizar mi cdigo.
Necesitar tenerlo todo en un archivo? Muchos tutoriales en la
Web que te ensean cmo escribir un servidor HTTP bsico en
Node.js tienen toda la lgica en un solo lugar. Qu pasa si yo
quiero asegurarme que mi cdigo se mantenga leble a medida
que le vaya agregando ms cosas?
Resulta, que es relativamente fcil de mantener los distintos
aspectos de tu cdigo separados, ponindolos en mdulos.
Esto te permite tener un archivo main limpio, en el cual
ejecutas Node.js, y mdulos limpios que pueden ser utilizados
por el archivo main entre muchos otros.
http://www.nodebeginner.org/index-es.html
9 / 52
12/10/2014
10 / 52
12/10/2014
11 / 52
12/10/2014
12 / 52
12/10/2014
13 / 52
12/10/2014
response.end();
}
http.createServer(onRequest).listen(8888);
14 / 52
12/10/2014
15 / 52
12/10/2014
16 / 52
12/10/2014
17 / 52
12/10/2014
18 / 52
12/10/2014
19 / 52
12/10/2014
20 / 52
12/10/2014
21 / 52
12/10/2014
22 / 52
12/10/2014
Por supuesto, este cdigo no est haciendo nada, pero eso est
bien por ahora. Empecemos a ver como vamos a encajar este
router con nuestro servidor antes de poner ms lgica en el
router.
Nuestro servidor HTTP necesita saber y hacer uso de nuestro
router. Podemos escribir directamente esta dependencia a
nuestro servidor, pero como hemos aprendido de la manera
difcil en nuestras experiencias, vamos a acoplar de manera
dbil (loose coupling en Ingls) al router y su servidor va
inyeccin por dependencia. Para una referencia de fondo, leer el
Artculo de Martin Fowler (en Ingls).
Primero extendamos nuestra funcin iniciar() de manera de
permitirnos pasar la funcin de ruteo a ser usada como
parmetro:
var http = require("http");
var url = require("url");
function iniciar(route) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Peticion para " + pathname + " recibida.");
route(pathname);
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Hola Mundo");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Servidor Iniciado.");
}
exports.iniciar = iniciar;
http://www.nodebeginner.org/index-es.html
23 / 52
12/10/2014
24 / 52
12/10/2014
25 / 52
12/10/2014
26 / 52
12/10/2014
27 / 52
12/10/2014
(N. del T.: Se Opta por dejar los verbos en Ingls 'route' para
rutear y 'handle' para manipular).
Au nqu e handle es ms una "cosa" (una coleccin de
manipuladores de peticin), Propongo que lo nombremos como
un verbo, ya que esto resultar en una expresin fluida en
nuestro router, como veremos a continuacin:
Como puedez ver, es realmente simple mapear diferentes URLs
al mismo manipulador de peticiones: Mediante la adicin de un
par llave/valor d e "/" y requestHandlers.iniciar, podemos
expresar en una forma agradable y limpia que no slo
peticiones a /start, sino que tambin peticiones a / pueden ser
manejadas por el manipulador inicio.
Despus de definir nuestro objeto, se lo pasamos al servidor
como un parmetro adicional. Modifiquemos nuestro server.js
para hacer uso de este:
var http = require("http");
var url = require("url");
function iniciar(route, handle) {
function onRequest(request, response) {
http://www.nodebeginner.org/index-es.html
28 / 52
12/10/2014
29 / 52
12/10/2014
30 / 52
12/10/2014
31 / 52
12/10/2014
Bloqueante y No-Bloqueante
Como se dijo, los problemas van a surgir cuando nosotros
incluyamos operaciones no-bloqueantes en los manipuladores
de peticin. Pero hablemos acerca de las operaciones
bloqueantes primero, luego, acerca de las operaciones nobloqueantes.
Y, en vez de intentar explicar que es lo que significa
"bloqueante" y "no bloqueante", demostremos nosotros mismo
que es lo que sucede su agregamos una operacin bloqueante a
nuestros manipuladores de peticin.
Para hacer esto, modificaremos nuestro manipulador de
peticin iniciar para hacer una espera de 10 segundos antes de
retornar su string "Hola Iniciar". Ya que no existe tal cosa como
sleep() en JavaScript, usaremos un hack ingenioso para ello.
http://www.nodebeginner.org/index-es.html
32 / 52
12/10/2014
33 / 52
12/10/2014
34 / 52
12/10/2014
35 / 52
12/10/2014
36 / 52
12/10/2014
37 / 52
12/10/2014
38 / 52
12/10/2014
Esto
har
que
las
peticiones
HTTP
a
http://localhost:8888/iniciar tomen al menos 10 segundos,
pero, las peticiones a http://localhost:8888/subir sean
respondidas inmediatamente, incluso si /iniciar todava est en
proceso.
39 / 52
12/10/2014
40 / 52
12/10/2014
41 / 52
12/10/2014
JavaScript o Node.js.
Mejor usemos el espacio que queda en pantalla para un
problema ms interesante, esto es, manipular la peticin POST
que dar con nuestro manipulador de peticin /subir cuando el
usuario enve este formulario.
Ahora que nos estamos convirtiendo en "novicios expertos", ya
no nos sorprende el hecho que manipular informacin de POST
este hecho de una manera no bloqueante, mediante el uso de
llamadas asincrnicas.
Lo que tiene sentido, ya que las peticiones POST pueden ser
potencialmente muy grandes - nada detiene al usuario de
introducir texto que tenga muchos megabytes de tamao.
Manipular este gran volumen de informacin de una vez puede
resultar en una operacin bloqueante.
Para hacer el proceso completo no bloqueante. Node.js le
entrega a nuestro cdigo la informacin POST en pequeos
trozos con callbacks que son llamadas ante determinados
eventos. Estos eventos son data (un nuevo trozo de informacin
POST ha llegado) y end (todos los trozos han sido recibidos).
Necesitamos decirle a Node.js que funciones llamar de vuelta
cuando estos eventos ocurran. Esto es hecho agregando
listeners (N. del T.: Del verbo listen - escuchar) al objeto de
peticin (request) que es pasado a nuestro callback onRequest
cada vez que una peticin HTTP es recibida.
Esto bsicamente luce as:
request.addListener("data", function(chunk) {
// funcion llamada cuando un nuevo trozo (chunk)
// de informacion (data) es recibido.
});
http://www.nodebeginner.org/index-es.html
42 / 52
12/10/2014
request.addListener("end", function() {
// funcion llamada cuando todos los trozos (chunks)
// de informacion (data) han sido recibidos.
});
http://www.nodebeginner.org/index-es.html
43 / 52
12/10/2014
}
http.createServer(onRequest).listen(8888);
console.log("Servidor Iniciado");
}
exports.iniciar = iniciar;
44 / 52
12/10/2014
45 / 52
12/10/2014
1019 Comments
Sort by Newest
Share
3 days ago
Well done! Thank you for this! It was really helpful, and well written.
1
Zurez
Reply Share
3 days ago
Reply Share
pasajero302
3 days ago
pinta bien parece mas facil que php...que php me parece muy engorro a medida que crece el codigo..... este hasta parece un
javascript like basic sintaxis
Tahir
Reply Share
12 days ago
hi there its very good thing learnt alot from this its very good tutorial but its too short :(
http://www.nodebeginner.org/index-es.html
46 / 52
iknowv
12/10/2014
Reply Share
18 days ago
Guest
Reply Share
19 days ago
Hola; muy interesante el tutorial la verdad es que el potencial de este libreria es fascinante. Pero me ha ocurrido un
inconveniente;estoy usando la version actual de Node y en la parte del router pues al intentar acceder al index me arroja error en
server.js en la linea de route(pathname). agradeceria si pudieras ayudarme con eso y de hecho es un magnifico tutorial uno de los
mas claros que he visto.
2
rex_devx
a month ago
Reply Share
Reply Share
krlos_19915991
a month ago
Hola, estoy intentando entender todo y seguir el ejemplo, pero me encuentro varado en el punto en el que requieres a
"requestHandlers" la primera ves en el index.js, luego creas el array handle, y se lo envias a la funcion server.iniciar. Es aqui donde
estoy varado, dado que modificas "server.iniciar" para enviarle este array recibido a la funcion tambien recibida (route) pero en
ninguna parte veo que modificas a "router.js" para que manipule el nuevo parametro que va a recibir, hasta ahi he logrado hacer
toda la aplicacion pero no he logrado mostrar los siguientes resultados
Servidor Iniciado.
Peticion para /iniciar recibida.
A punto de rutear una peticin para /iniciar
Manipulador de peticion 'iniciar' ha sido llamado.
me podrian ayudar? me interesa mucho seguir con la aplicacion y estoy estancado.
Gracias
Reply Share
25 days ago
Krlos, para que el ejemplo funcione en ese punto route.js tiene que quedar de la siguiente forma:
function route(handle, pathname) {
console.log("A punto de rutear una peticion para " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname]();
}
}
exports.route = route;
El if es para que la aplicacin no se cuelgue cuando el browser intenta cargar el favicon. Igualmente si continus con el tutorial
el cdigo de los ejemplos se reacomoda y se pueden comprender bien todos los conceptos.
Saludos.
1
Aymen
Reply Share
a month ago
Wow what a great tutorial for learning node. Also teaches best code practices and pitfalls to avoid!
Well worth the money spent!
2
naeem
Reply Share
a month ago
very nice tutorial. I have been learning node js for last 1 year, and this tutorial is really wonderful for everyone
2
HL
Reply Share
a month ago
Just bought the bundle. I think there's an error on page 38, line 20 of the craftsman book. It should be "watcher.on('shrank',..."?
Also, when can we expect the remaining chapters?
Reply Share
http://www.nodebeginner.org/index-es.html
47 / 52
zam
12/10/2014
a month ago
Ignore my previous question, I hadn't read the "Fee lifetime updates" thing.
1
zam
Reply Share
a month ago
Does the bundle price include the final version of "The Node Craftsman Book"?
1
Reply Share
Bruno Casanova
a month ago
The best tutorial i've ever seen of Node.js! Very thanks Man!!
1
eddnav
Reply Share
a month ago
Best in class material, I truly thank you for this, If I had the possibility I would buy it, alas I'm stuck in this god forsaken country.
3
Paolo
Reply Share
a month ago
Manuel, this is one of the clearest explanation on programming language I ever came across! Already bought the books.
I plan to use it for the communication with my self balancing robot, at the moment I am using python but it is a pain:
https://plus.google.com/100167...
2
Reply Share
Manuel Kiessling
David Howell
Reply Share
a month ago
Hi, great tutorial. i tried to modify it to upload a jpg and got the following error. on the final set of modifications. (it worked up until
then). any idea where i went wrong?
fs.rename(files.upload.path, "temp/test.jpg", function(error)
^
TypeError: Cannot read property 'path' of undefined
at /Users/davidhowell/Programs/requestHandlers.js:37:25
at IncomingForm.<anonymous> (/Users/davidhowell/Programs/node_modules/formidable/lib/incoming_form.js:101:9)
at IncomingForm.emit (events.js:95:17)
at IncomingForm._error (/Users/davidhowell/Programs/node_modules/formidable/lib/incoming_form.js:289:8)
at IncomingMessage.<anonymous> (/Users/davidhowell/Programs/node_modules/formidable/lib/incoming_form.js:131:14)
at IncomingMessage.emit (events.js:92:17)
at _stream_readable.js:943:16
at process._tickCallback (node.js:419:13)
Reply Share
a month ago
Hi David, I think I had a similar problem (You don't make it clear whether the *.png worked or not). Resolving it came down to
ensuring that I had the correct html and then ensuring that I ran with a fresh server and ensuring that the start page had
been properly refreshed in the browser.
Hope this helps.
Christian Gitter
Reply Share
a month ago
Reply Share
Samuel Viana
a month ago
Very helpful hands-on on-line book for a quick start with Node.js . The essential concepts are here.
http://www.nodebeginner.org/index-es.html
48 / 52
12/10/2014
Reply Share
Suriyaa Kudo
a month ago
salman
Reply Share
a month ago
hi
I am using asp.net for 6 years, is there any reason to turn into node.js?
1
Reply Share
Manuel Kiessling
Well, there is no simple or even "true" answer to that. The Node.js approach is very different from the ASP approach.
Therefore, building some kinds of network applications with ASP will feel more natural, building other kinds of network
applications will feel more natural with Node.js.
Maybe you can find an answer if you try to build a web chat system with Node.js - there are a lot of tutorials available for this.
You will then be able to decide if building the same system with ASP would have felt equally natural.
2
optimisto1 .
Reply Share
a month ago
Reply Share
Richard Foss
2 months ago
Hi Manuel, thanks for the book, just started going through it. In the code for server.js on page 20, should there be a
var router = require("./router");
Richard.
Reply Share
Manuel Kiessling
No, that's not neccessary; you inject the route function from the router module in the index.js file, passing it as a parameter
to server.start().
Reply Share
2 months ago
Thanks - one other thing - presumably a semicolon needed on line 5 of index.js on page 23?
1
Reply Share
Manuel Kiessling
Reply Share
2 months ago
I wish there was an HTML option as well. The formatting, as well as the fact that you can just keep the tutorial running in a browser
tab, was quite nice. I've got the PDF loaded in a tab, but the formatting is constantly remind you "this is a book." I don't need page
breaks and line numbers :]
Reply Share
Manuel Kiessling
That is a valid point. Leanpub currently doesn't generate HTML; however, the source format of the book is Markdown, thus it
shouldn't be such a great deal to generate a decent HTML page from it. I will look into that.
2
jmz
Reply Share
2 months ago
Really well written!! I initially had some trouble with routing, but after a few re-tries, I got it working! Thanks for this node.js
introduction.
1
omar
Reply Share
2 months ago
Hola, muy bueno tu artculo, pero ms o menos a la mitad comenc a notar que parece que le faltan prrafos y cdigo. Por ejemplo:
http://www.nodebeginner.org/index-es.html
49 / 52
12/10/2014
Reply Share
20 days ago
jow
Reply Share
2 months ago
Reply Share
2 months ago
Why.
manikanta
Reply Share
3 months ago
My hat flips to You sir! With this blog i've started learning node.js! :)
3
Reply Share
Vijay Rules
3 months ago
Reply Share
Elia Lombardi
3 months ago
Reply Share
Manuel Kiessling
Hi Elia,
sorry for getting back to you quite late. I have updated the PDF on Leanpub.
ray
Reply Share
3 months ago
Copying the code from the website works fine, but copying from the pdf or epub includes the lines number and strange formatting
Reply Share
Leon Guan
3 months ago
Very good read, easy to follow, very clear, found this and needed something like this to research upon and play around with it. I am
a Newbie in programming, never could get a hang of it, but i guess we all got to start somewhere! :)
1
Giuseppe
3 months ago
Reply Share
Hi, I installed node on my personal laptop. I have a web site hosted on a server, how can I install node there so to have my node.js
code accessible to public? Thanks.
5
Fran Pugh
Reply Share
3 months ago
I have hit a problem right at the last bit. It gets to 'about to parse' and then fails on parsing the form with TypeError: Cannot read
property 'content-length' of undefined. I cant see what I've done wrong
http://www.nodebeginner.org/index-es.html
50 / 52
12/10/2014
Reply Share
Manuel Kiessling
Hi Fran,
please let me know what version of Node and node-formidable you use, and which version of what browser on what platform.
Reply Share
3 months ago
Anthony Ogbonna
Reply Share
3 months ago
Help! I can't make the purchase. Your payment system is rejecting my card. I really need to get this.
Reply Share
Manuel Kiessling
Peeyush Singh
Reply Share
3 months ago
Reply Share
Load more comments
Subscribe
http://www.nodebeginner.org/index-es.html
Privacy
51 / 52
12/10/2014
The Node Beginner Book by Manuel Kiessling (see Google+ profile) is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Permissions beyond the scope of this license may be available at manuel@kiessling.net.
http://www.nodebeginner.org/index-es.html
52 / 52