Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Up and Running with Node.

js
Up and Running with Node.js
Tom Hughcs-Crouchcr
Beijing Cambridge Farnham Kln Sebastopol Tokyo
Up and Running with Node.js
Ly Tom Hughes-Ciouchei
Copyiight 2010 . All iights ieseiveu.
Editor: Simon St.Lauient
Printing History:
ISBN: 97S-1-++9-39S5S-3
12S9319959
Table of Contents
Author's Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
A veiy Liiel intiouuction to Noue.js. 1
Part I. Core Concepts
2. Why Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1 Piolessionalism in ]avaSciipt 5
2.2 Biowsei Vais 2.0 6
3. Understanding Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.1 The Event Loop 9
Part II. Writing Code with Node.js
4. Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.1 Installing Noue.js 17
5.2 Fiist steps in coue 22
5.2.1 Noue REPL 22
5.2.2 My Fiist Seivei 23
v
Author's Note
Vhen Simon, my euitoi, anu I weie initially uiscussing this pioject it was oLvious how
viLiant the Noue.js community is. Ve lelt that it was impoitant that we engageu with
the community as we woikeu on this manusciipt. In oiuei to uo that we ueciueu to
ielease the Look in paits as I wiote it. Vhat you aie ieauing now is one ol those paitial
ieleases.
Vhat you'll linu within this liist ielease is not necessaiily the linal woik that we will
puLlish. Ve hope Ly making this Look availaLle as it's wiitten we'll get youi leeuLack,
iueas anu thoughts on what I've alieauy wiitten anu what else we shoulu Le coveiing.
Not only that, Lut Noue is giowing almost lastei than I can keep up with it. Not to
mention the community mouules which aie giowing even lastei than that. Beloie we
go to piess we'll make suie that the inloimation in the text is up to uate with the latest
veision ol Noue, anu that we haven't misseu any ciitical contiiLutions liom the com-
munity that neeu to Le coveieu.
You can pioviue youi leeuLack Ly emailing me at cioucheiyahoo-inc.com.
--Ton
vii
Preface
Conventions Used in This Book
The lollowing typogiaphical conventions aie useu in this Look:
|ta|ic
Inuicates new teims, URLs, email auuiesses, lilenames, anu lile extensions.
Constant width
Useu loi piogiam listings, as well as within paiagiaphs to ielei to piogiam elements
such as vaiiaLle oi lunction names, uataLases, uata types, enviionment vaiiaLles,
statements, anu keywoius.
Constant width bold
Shows commanus oi othei text that shoulu Le typeu liteially Ly the usei.
Constant width italic
Shows text that shoulu Le ieplaceu with usei-supplieu values oi Ly values uetei-
mineu Ly context.
This icon signilies a tip, suggestion, oi geneial note.
This icon inuicates a waining oi caution.
Using Code Examples
This Look is heie to help you get youi joL uone. In geneial, you may use the coue in
this Look in youi piogiams anu uocumentation. You uo not neeu to contact us loi
peimission unless you`ie iepiouucing a signilicant poition ol the coue. Foi example,
wiiting a piogiam that uses seveial chunks ol coue liom this Look uoes not ieguiie
peimission. Selling oi uistiiLuting a CD-ROM ol examples liom O`Reilly Looks uoes
ix
ieguiie peimission. Answeiing a guestion Ly citing this Look anu guoting example
coue uoes not ieguiie peimission. Incoipoiating a signilicant amount ol example coue
liom this Look into youi piouuct`s uocumentation uoes ieguiie peimission.
Ve appieciate, Lut uo not ieguiie, attiiLution. An attiiLution usually incluues the title,
authoi, puLlishei, anu ISBN. Foi example: Boo| Tit|c Ly Some Authoi (O`Reilly).
Copyiight 2011 Some Copyiight Holuei, 97S-0-596-xxxx-x.
Il you leel youi use ol coue examples lalls outsiue laii use oi the peimission given aLove,
leel liee to contact us at pcrnissionsorci||y.con.
Safari Books Online
Salaii Books Online is an on-uemanu uigital liLiaiy that lets you easily
seaich ovei 7,500 technology anu cieative ieleience Looks anu viueos to
linu the answeis you neeu guickly.
Vith a suLsciiption, you can ieau any page anu watch any viueo liom oui liLiaiy online.
Reau Looks on youi cell phone anu moLile uevices. Access new titles Leloie they aie
availaLle loi piint, anu get exclusive access to manusciipts in uevelopment anu post
leeuLack loi the authois. Copy anu paste coue samples, oiganize youi lavoiites, uown-
loau chapteis, Lookmaik key sections, cieate notes, piint out pages, anu Lenelit liom
tons ol othei time-saving leatuies.
O`Reilly Meuia has uploaueu this Look to the Salaii Books Online seivice. To have lull
uigital access to this Look anu otheis on similai topics liom O`Reilly anu othei puL-
lisheis, sign up loi liee at http://ny.sajariboo|son|inc.con.
How to Contact Us
Please auuiess comments anu guestions conceining this Look to the puLlishei:
O`Reilly Meuia, Inc.
1005 Giavenstein Highway Noith
SeLastopol, CA 95+72
S00-99S-993S (in the Uniteu States oi Canaua)
707-S29-0515 (inteinational oi local)
707-S29-010+ (lax)
Ve have a weL page loi this Look, wheie we list eiiata, examples, anu any auuitional
inloimation. You can access this page at:
http://www.orci||y.con/cata|og/<cata|og pagc>
To comment oi ask technical guestions aLout this Look, senu email to:
boo|qucstionsorci||y.con
x | Preface
Foi moie inloimation aLout oui Looks, conleiences, Resouice Centeis, anu the O`Re-
illy Netwoik, see oui weLsite at:
http://www.orci||y.con
Preface | xi
CHAPTER 1
Introduction
A very brief introduction to Node.js.
Noue.js is many things, Lut mostly it's a way ol iunning ]avaSciipt outsiue the weL
Liowsei. This Look will Le coveiing in uetail why that's impoitant, anu what Lenelits
Noue.js pioviues. This intiouuction attempts to sum up that explanation into a lew
paiagiaphs, iathei than a lew hunuieu pages.
Many people use the ]avaSciipt piogiamming languages extensively loi piogiamming
the inteilaces ol VeL sites. Noue.js allows this populai piogiamming language to Le
applieu in many moie contexts, in paiticulai on the seiveis that iun VeL sites. Theie
aie seveial uistinct oi notaLle leatuies aLout Noue.js that make it woithy ol youi in-
teiest.
Noue is a ]avaSciipt iuntime. It is actually a wiappei aiounu the VS ]avaSciipt iuntime
liom the Google Chiome Liowsei. The VS implementation ol ]avaSciipt is extiemely
last anu peiloims veiy well in many ciicumstances. Noue tunes VS to woik Lettei in
contexts othei than the Liowsei, mostly Ly pioviuing alteinative APIs which aie opti-
mizeu loi specilic use cases. Foi example, in a seivei context the manipulation ol Linaiy
uata is olten necessaiy. This is pooily suppoiteu Ly ]avaSciipt anu as a iesult, VS. Noue
auueu the Buffer class to its implementation to allow easy manipulation ol Linaiy uata
in a way which is Loth easy to use anu memoiy ellicient. As such Noue uoesn't just
pioviue uiiect access to the VS ]avaSciipt iuntime it also makes it moie uselul loi the
contexts in which people use Noue.
VS itsell uses some ol the newest technigue complilei technology. This allows the coue
wiitten in a high-level langauge like ]avaSciipt to peiloim as well as coue wiitten in
much lowei level languages like C with a liaction ol the uevelopment cost. This locus
on peiloimance is a key aspect ol Noue.
]avaSciipt is a veiy event uiiven language, anu Noue uses this to its auvantage to pio-
uuce highly scalaLle seiveis. Using an aichitectuie calleu an event loop, Noue makes
piogiamming high scalaLle seiveis Loth easy anu sale. Theie aie vaiious stiategies that
aie useu to make seiveis peiloimant. Noue has chosen an aichitectuie that peiloims
1
veiy well Lut also ieuuces the complexity loi the application uevelopei. This is an
extiemely impoitant leatuie. Piogiamming concuiiency is haiu, anu liought with uan-
geis. Noue siue-steps these while still olleiing impiessive peiloimance. As always any
ppioach still has tiaue-olls whcih aie uiscusseu in uetail latei in the Look.
Suppoiting the event-loop appioach Noue takes aie a set ol "non-Llocking" liLiaiies.
In essence these aie inteilaces to things like the lilesystem oi uataLases which uo so in
an event-uiiven way. Vhen you want to make a ieguest to the lile system iathei than
ieguiiing Noue to wait loi the haiu uiive (to spin up anu ietiive the lile) the non-
Llocking inteilace simply notilies Noue when it has access. This mouel simplilies access
to slow iesouices in a scalaLle way that is intuitive to ]avaSciipt piogiammeis anu easy
to leain loi eveiyone else. In paiticulai loi anyone lamiliai with uealing with DOM
events like onmouseovei oi onclick in the Liowsei it is extiemely lamiliai.
Vhile not unigue to Noue suppoiting ]avaSciipt on the seivei is also a poweilul leatuie.
Vhethei we like it oi not the Liowsei enviionment gives us little choice ol piogiamming
languages. Ceitainly il we woulu like oui coue to woik in any ieasonaLle peicentage
ol Liowseis ]avaSciipt is the only choice. Any aspeiations to shaie coue Letween the
seivei anu the incieasingly complex client applications we aie Luiluing in the Liowsei
must Le uone with ]avaSciipt. Vhile theie aie othei platloims which suppoit pio-
giamming weL seiveis with ]avaSciipt, Noue is guickly gaining suppoit as the uelacto
platloim loi the ieasons aLove.
Asiue liom what you can Luilu with Noue, one extiemely pleasing aspect is how much
you can Luilu loi Noue. Noue is extiemely extensiLle with a laige volume ol community
liLiaiies (oi mouules) having Leen Luilt in the shoit time the pioject has Leen iunning.
Many ol these aie uiiveis to connect with uataLases oi othei soltwaie, Lut many aie
also uselul soltwaie applications in theii own iight.
Last Lut ceitainly not least, is the Noue community. The Noue pioject is still veiy
young, anu yet iaiely has the authoi seen such luivoi aiounu a pioject. Both novices
anu expeits have coalleseu aiounu the pioject to use anu contiiLute to Noue making
it a pleasuie to exploie anu suppoitive places to shaie anu get auvice.
2 | Chapter 1:Introduction
PART I
Core Concepts
CHAPTER 2
Why Node
In wiiting this Look I've Leen acutely awaie ol how new Noue.js is. Many platloims
take yeais to linu auoption, anu yet I've lounu a level ol excitement aiounu Noue.js
that I've nevei seen Leloie in such a young platloim. I hope that Ly looking at why
people aie getting so exciteu aLout Noue.js I will explain why it may also Le inteiesting
to you. By looking at Noue.js' stiengths we can linu the the places wheie it is most
applicaLle. This chaptei will look at the lactois that have come togethei to cieate a
space loi Noue.js anu look at the ieasons why it's Lecome so populai in such as shoit
time.
2.1 Professionalism in JavaScript
]avaSciipt was cieateu Ly Bienuan Eich in 1995 to Le a simple sciipting language loi
use in weL pages on the Netscape Liowsei platloim. Suipiisingly almost since its in-
ception ]avaSciipt has Leen useu in non-Liowsei settings. Some ol the eaily Netscape
seivei piouucts suppoiteu ]avaSciipt (known then as LiveSciipt) as a seivei-siue sciipt-
ing language. Sauly, howevei seivei-siue ]avaSciipt uiun't ieally catch on. That ceitainly
wasn't tiue loi the VeL which exploueu in the coming yeais. On the VeL ]avaSciipt
competeu with Miciosolt's VBSciipt to pioviue piogiamming lunctionality in VeL
pages. It's haiu to say why ]avaSciipt won, peihaps Miciosolt's ]Sciipt a ]avaSciipt
clone, oi just the language itsell, Lut win it uiu. This meant Ly the eaily 2000s ]avaSciipt
hau emeigeu as thc VeL language. Not the liist choice, Lut the on|y choice loi pio-
giamming with HTML in Liowseis.
Vhat uoes this have to uo with Noue.js? Vell the impoitant thing to iememLei is that
when the A]AX ievolution happeneu anu the VeL Lecame Lig Lusiness (think Yahoo,
Amazon, Google, etc) the only choice loi the "]" in A]AX was ]avaSciipt theie simply
wasn't an alteinative. As a iesult a whole inuustiy neeueu an awlul lot ol ]avaSciipt
piogiammeis, ieally goou ones at that, iathei last. The emeigence ol the VeL as a
seiious platloim anu ]avaSciipt as its piogiamming language meant that we, as ]ava-
Sciipt piogiammeis neeueu to shape up. Ve can eguate the change in ]avaSciipt as the
seconu oi thiiu piogiamming language ol a piogiammei to the change in peiception
5
ol its impoitance. Ve staiteu to get emeiging expeits who leau the chaige in making
]avaSciipt iespectaLle.
AiguaLly at the heau ol this movement was Douglas Ciockloiu. His populai aiticles
anu viueos on ]avaSciipt have helpeu many piogiammeis uiscovei that insiue a lan-
guage much maligneu theie is a lot ol innei Leauty. Most piogiammeis woiking with
]avaSciipt hau spent the majoiity ol theii time woiking with the Liowsei implemen-
tation ol the V3C DOM API loi manipulating HTML oi XML uocuments. Unloitu-
nately, the DOM is pioLaLly not the piettiest API evei conceiveu, Lut woise its vaiious
implementations in the Liowseis aie inconsistent anu incomplete. No wonuei that loi
a uecaue altei its ielease ]avaSciipt was not thought ol as a "piopei" language Ly so
many piogiammeis. Moie iecently Douglas' woik on "the goou paits" ol ]avaSciipt
have helpeu cieate a movement ol auvocates ol the language which iecognize that it
has a lot going loi it uespite the waits.
In 2010 we now have a piolileiation ol ]avaSciipt expeits auvocating well wiitten,
peiloimant, maintainaLle ]avaSciipt coue. People such as Douglas Ciockloiu, Dion
Almaei, Petei Paul Koch (PPK), ]ohn Resig, Alex Russell, Thomas Fuchs, anu many
moie have pioviueu ieseaich, auvice, tools, anu piimaiily liLiaiies that have alloweu
thousanus ol piolessional ]avaSciipt piogiammeis woiluwiue to piactice theii tiaue
with a spiiit ol excellence. LiLiaiies like jQueiy, YUI, Dojo, Piototype, Mootools, Sen-
cha anu many otheis aie now useu uaily Ly thousanus ol people anu ueployeu on
millions ol VeL sites. It is in this enviionment wheie ]avaSciipt is not only accepteu,
Lut wiuely useu anu celeLiateu that a platloim laigei than the weL makes sense. Vhen
so many piogiammeis know ]avaSciipt its uLiguity has Lecome a uistinct auvantage.
Vhen I speak at conleiences I can ask a ioom lull ol VeL piogiammeis what languages
they use. ]ava anu PHP aie veiy populai, RuLy is pioLaLly next most populai these
uays oi at least closely tieu with Python anu Peil still has a huge lollowing. Howevei,
almost without exception anyone who uoes any piogiamming loi the weL has pio-
giammeu in ]avaSciipt. Vhile Lackenu languages aie liactuieu in Liowsei piogiam-
ming is uniteu Ly the necessities ol ueployment. Vaiious Liowseis anu Liowsei plugins
allow the use ol othei languages, Lut they simply aien't univeisal enough loi the weL.
So heie we aie with a single univeisal weL language. How can we get it on the seivei?
2.2 Browser Wars 2.0
Faiily eaily in the uays ol the VeL we hau the inlamous browscr wars. Inteinet Exploiei
anu Netscape competeu viciously on VeL leatuies, auuing vaiious incompatiLle pio-
giammatic leatuies to theii Liowseis anu not suppoiting the leatuies in the othei
Liowsei. Foi those ol us who piogiammeu the weL this was the cause ol much anguish
Lecause it maue VeL piogiamming ieally tiiesome. Inteinet Exploiei moie oi less
emeigeu the winnei ol that iounu anu Lecame the uominant Liowsei. Fast loiwaiu a
lew yeais, Inteinet Exploiei has Leen languishing at veision 6 anu a new contenuei,
Fiielox emeiges liom the iemnants ol Netscape. Fiielox kicks oll a new iesuigence in
6 | Chapter 2:Why Node
Liowseis Leing lolloweu Ly VeLkit (Salaii) anu then Chiome. Most inteiesting aLout
this cuiient tienu is the iesuigence ol competition into the Liowsei maiket.
Unlike the liist iteiation ol the Liowsei wais touay's Liowsei compete on two lionts,
auheiing to the stanuaius that emeigeu altei the pievious Liowsei wai anu peiloim-
ance. As VeL sites have Lecome moie complex useis want the lastest expeiience pos-
siLle. This has meant that Liowseis not only neeu to suppoit the VeL stanuaius well,
allowing uevelopeis to optimize, Lut also to uo a little optimization ol theii own. ]ava-
Sciipt Leing a coie component ol VeL 2.0, A]AX weL sites has Lecome pait ol the
Lattlegiounu.
Each Liowsei has theii own ]avaSciipt iuntimes: Spiuei Monkey loi Fiielox, Sguiiiel
Fish Extieme loi Salaii, Kaiakan loi Opeia, anu linally VS loi Chiome. As these iun-
times compete on peiloimance it cieates an enviionment ol innovation loi ]avaSciipt.
In oiuei to uilleientiate theii Liowseis venuois aie going to gieat lengths to make them
as last as possiLle.
2.2 Browser Wars 2.0 | 7
CHAPTER 3
Understanding Node.js
In oiuei to make the most out ol the SeiveiSiue ]avaSciipt enviionment it's impoitant
to unueistanu some coie concepts Lehinu the uesign choices that weie maue loi Noue.js
anu ]avaSciipt in geneial. Unueistanuing the uecisions anu tiaueolls will make it easiei
loi you to wiite gieat coue anu aichitect youi systems. It will also help you explain to
othei people why Noue.js is uilleient liom othei systems they've useu anu wheie the
peiloimance gains come liom. No engineei likes unknowns in theii systems. "Magic"
is not an acceptaLle answei so it helps to Le aLle to explain why a paiticulai aichitectuie
is Lenelicial anu unuei what ciicumstances.
3.1 The Event Loop
A lunuamental pait ol Noue is the event loop. The event loop is a concept that has Leen
lunuamental to ]avaSciipt since its inception Lut moie iecently has Leen auapteu loi
application as a high peiloimance computing platloim. In many languages event mou-
els aie Lolteu on the siue, howevei in ]avaSciipt events have always Leen a coie pait ol
the language. This is Lecause ]avaSciipt has always uealt with usei inteiaction. Anyone
who has useu a mouein VeL Liowsei is useu to VeL pages that uo things "onclick",
"onmouseovei", etc. These events aie so common that we haiuly think aLout them
when wiiting VeL page inteiaction, Lut having this event suppoit in the language is
incieuiLly poweilul. On the seivei we uon't have the limiteu set ol events Laseu on a
usei-uiiven inteiaction with the VeL page DOM, insteau we have an inlinite vaiiety
ol events Laseu on what is happening in the seivei soltwaie we use. Foi example, the
HTTP seivei mouule pioviues an event calleu "ieguest". This event is emitteu when a
usei senus the VeL seivei a ieguest.
The event loop is the system that ]avaSciipt uses to ueal with these incoming ieguest
liom vaiious paits ol the system in a sane mannei. Theie aie a numLei ol ways people
ueal with 'ieal-time' oi 'paiallel' issues in computing. Most ol them aie laiily complex
anu liankly make my Liain huit. ]avaSciipt takes a simple appioach that makes the
piocess much moie unueistanuaLle Lut uoes intiouuce a lew constiaints. By having a
9
giasp ol how the event loop woiks you'll Le aLle to use it to it's lull auvantage anu avoiu
the pitlalls ol this appioach.
On the seivei theie isn't a usei to uiive a vaiiety ol inteiactions. Insteau we have a whole
iange ol ieactions to take on many uilleient kinus ol events. Noue takes the appioach
that all I/O activities shoulu Le non-Llocking (loi ieasons we'll explain moie latei). This
means that all HTTP ieguests, uataLase gueiies, lile I/O, etc uo not halt execution until
they ietuin, insteau they iun inuepenuently anu then emit an event when the uata is
availaLle. This means that piogiamming in Noue.js has lots ol callLacks uealing with
all kinus ol I/O anu then initiating othei callLacks loi othei kinus ol I/O. This is a veiy
uilleient liom Liowsei piogiamming. Theie is still a ceitain amount ol lineai setup,
Lut the Lulk ol the coue involves uealing with callLacks.
Because ol these uilleient piogiamming styles we neeu to look loi patteins to help us
ellectively piogiam on the seivei. That staits with the event loop. I think that most
people intuitively get event uiiven piogiamming Lecause it's like eveiy uay lile. Imagine
you aie cooking. You aie chopping a Lell peppei anu a pot staits to Loil ovei. You linish
the slice you aie uoing, anu then tuin uown the stove. In eveiy uay lile we aie useu to
having all soits ol inteinal callLacks loi uealing with events, anu yet, like ]avaSciipt,
we only evei uo one thing at once. Yes, yes, I can see you aie iuLLing youi tummy anu
patting youi heau at the same time, well uone. But, il you tiy to uo any seiious activities
at the same time it goes wiong pietty guick. This is like ]avaSciipt. It's gieat at letting
events uiive the action, Lut it "single-thieaueu" so only one thing happens at once.
This single-thieaueu concept is ieally impoitant. One ol the ciiticisms leveleu at
Noue.js laiily olten is it's lack ol "concuiiency". That is, it uoesn't use all ol the CPUs
on a machine in oiuei to iun the ]avaSciipt. Ciitics suggest that Noue shoulu pioviue
access to iun coue on multiple CPUs at once. The pioLlem with this appioach is that
it ieguiies co-oiuination Letween multiple "thieaus" ol execution. In oiuei to ellectively
split up some woik that neeus uoing acioss multiple CPUs they woulu have to Le aLle
to talk to each othei aLout the cuiient state ol the piogiam, what woik they'u each
uone, etc. Vhile this is possiLle, it's a moie complex mouel which ieguiies moie com-
Iigurc 3-1. Evcnt Drivcn Pcop|c
10 | Chapter 3:Understanding Node.js
plexity liom Loth the piogiammei anu the system. ]avaSciipt's appioach is simple,
theie is only one thing happening at once. This is simple to unueistanu. Since eveiything
that Noue uoes is non-Llocking the time Letween an event Leing emitteu anu Noue
Leing aLle to act on that event is veiy small, Lecause it's not waiting on things like uisk
I/O.
Anothei way to think aLout the event loop is a post (mail) man. To oui event loop
postman each lettei is an event. He has a stack ol events to uelivei in oiuei. Foi each
lettei (event) the postman gets he walks to the ioute to uelivei the lettei. The ioute is
the callLack lunction assigneu to that event (sometimes moie than one). Howevei,
ciitically, since oui mailman only has a single set ol legs he can only walk a single coue
path at once. Sometimes, while the postman is walking a coue ioute someone will give
him anothei lettei. This is the callLack lunction he is coue walking emitting an event.
In this case the postman ueliveis the new message immeuiately (altei all someone gave
it to him uiiectly insteau ol going via the post ollice so it must Le uigent). The postman
will uiveige liom his cuiient coue path anu walk the coue path to uelivei the new event.
He then caiiies on walking the oiiginal event that emitteu the event he just walkeu.
Let's look at the Lehavioi ol oui postman in a typical piogiam Ly picking something
ieally simple. Suppose we have a VeL (HTTP) seivei that get ieguests, ietiieves some
uata liom a uataLase anu ietuins it to the usei. In this scenaiio we have a lew events
to ueal with. Theie is the request event when a usei asks the VeL seivei loi a VeL
page anu the response event when the uataLase has lounu the gueiy we want. A usei
Iigurc 3-2. Thc cvcnt |oop post nan
3.1 The Event Loop | 11
asks loi a VeL page, this causes the seivei to issue a request event. The lunctional that
ueals with this ieguest (the callLack) looks at the ieguest oLject anu liguies out what
uata it neeus liom the uataLase. It then makes a ieguest to the uataLase loi that uata,
passing anothei callLack lunction to Le calleu on the response event. Vhen the uata-
Lase has lounu the uata it calls response which senus the uata Lack to the usei.
This seems laiily stiaight loiwaiu. The oLvious things to note heie aie the "Lieak" in
the coue which you woulun't get in a pioceuuial system. Since Noue.js is non-Llocking
system when we get to the uataLase call woulu make us wait, we insteau issue a callLack.
This means that theie is a "Lieak" Letween when the callLack was issueu anu when it
is calleu. As such we neeu to make suie that we pass any state we neeu to the callLack,
oi make it availaLle in some othei way. The typical way that this is uone in ]avaSciipt
piogiamming is using closuies. Ve'll uiscuss that in moie uetail latei.
Let's look at anothei example. Let's give the postman a lettei to uelivei that ieguiies a
gate to Le open. He gets theie anu the gate is closeu, so he simply waits anu tiies again,
anu again. He's tiappeu in an enuless loop waiting loi the gate to open. But theie is a
lettei on the stack that will ask someone to open the gate so the postman can get
thiough, suiely that will solve things, iight? Unloitunately it won't Lecause the postman
Iigurc 3-3. B|oc|ing thc cvcnt |oop
12 | Chapter 3:Understanding Node.js
will nevei get to uelivei the lettei Lecause he's stuck waiting enulessly loi the gate to
open. This is Lecause the event that opens the gate is exteinal the cuiient event callLack.
Il we emit the event liom within a callLack we alieauy know oui postman will go anu
uelivei that lettei Leloie caiiying on, howevei when events aie emitteu exteinal to the
cuiiently executing piece ol coue they will not Le calleu until that piece ol coue has
Leen lully evaluateu to its conclusion. Ve can use this to wiite a piece ol coue that
cieates a loop that Noue.js (oi a Liowsei) will nevei Lieak out ol:
Exanp|c 3-1. Evcnt |oop b|oc|ing codc
EE = require('events').EventEmitter;
ee = new EE();
die = false;
ee.on('die', function() {
die = true;
});
setTimeout(function() {
ee.emit('die');
}, 100);
while(!die) {
}
console.log('done');

In this example console.log will nevei Le calleu Lecause the while loop stops Noue liom
evei getting chance to callLack the timeout anu emit the 'die' event. This is a ieally
impoitant piece ol inloimation, Lecause while it's unlikely we'u piogiam a loop like
this that ielies on an exteinal conuition to exit, it cleaily illustiates how Noue.js can
only uo one thing at once, anu getting a lly in the ointment can ieally sciew up the
whole seivei. Let's look at the stanuaiu Noue.js coue loi cieating an HTTP seivei:
Exanp|c 3-2. A basic HTTP scrvcr
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/'

This coue is the 101 example liom the Noue.js VeL site. It cieates an HTTP seivei
using a lactoiy methou in the http liLiaiy. The lactoiy methou cieates a new HTTP
3.1 The Event Loop | 13
seivei anu attaches a callLack to the 'request' event. The callLack is specilieu as the
aigument to the createServer. Vhat's inteiesting heie is what happens when this coue
is iun. The liist thing Noue.js uoes is iun the coue aLove liom top to Lottom. This can
Le consiueieu the 'setup' phase ol Noue piogiamming. Since we attacheu some event
listeneis Noue.js uoesn't exit, Lut waits loi an event to Le liieu. Il we uiun't attach any
events then Noue.js woulu exit as soon as it hau iun the coue.
So what happens when we get an HTTP ieguest? Vhen an HTTP ieguest is sent to the
seivei Noue.js emits the 'ieguest' event which causes the callLacks attacheu to that
event to Le iun in oiuei. In this case theie is only one callLack, the anonymous lunction
we passeu as an aigument to createServer. Let's assume it's the liist ieguest the seivei
has hau since it setup. Since theie is no othei coue iunning the 'request' event is
emitteu anu the callLack is just iun. It's a veiy simple callLack anu it iuns pietty last.
Let's assume that oui site gets ieally populai anu we get lots ol ieguests. Il, loi the sake
ol aigument, oui callLack takes 1 seconu, then il we got 2 ieguests at the same time
they can't Loth Le iun at once, anu the seconu ieguest isn't going to Le acteu on loi
anothei seconu, oi so. OLviously, a seconu is a ieally long time Lut as we stait to look
at ieal woilu applications the pioLlem ol Llocking the event loop Lecomes moie uan-
geious as we can see the uamage it coulu have on useis. The upshot ol this is that we
want to keep Noue.js as event-uiiven anu non-Llocking as possiLle. In the same way
that I/O event that can Le slow shoulu use callLacks to inuicate the piesence ol uata
Noue.js can act on, the Noue.js piogiam itsell shoulun't Le wiitten in such a way as
any single callLack ties up the event loop loi extenueu pieces ol time. The opeiating
system keinel actually hanules the TCP connections to clients loi the HTTP seivei, so
theie isn't a iisk ol not accepting new connections, Lut theie is a ieal uangei ol not
acting on them.
This means that we shoulu employ two stiategies loi wiiting Noue.js seiveis:
Once set up has Leen completeu make all actions event uiiven
Il Noue.js is ieguiieu to piocess something that will take a long time consiuei
uelegating with VeL woikeis
Taking the event uiiven appioach woiks ellectively with the event loop (I guess the
name is hint it woulu), Lut it's also impoitant to wiite event uiiven coue in a way which
is easy to ieau anu unueistanu. In the pievious example we useu an anonymous lunc-
tion as the event callLack, this makes things haiu in a couple ol ways. Fiistly we have
no contiol ovei wheie the coue lives, the anonymous lunction must live wheie it is
attacheu to the event eithei via a lactoiy methou oi the on methou ol an EventEmittei.
The seconu issue is ueLugging, il eveiything is an anonymous event it can sometimes
Le haiu to uistinguish similai callLacks liom each othei when an exception occuis.
14 | Chapter 3:Understanding Node.js
PART II
Writing Code with Node.js
CHAPTER 4
Getting Started
5.1 Installing Node.js
Installing Noue.js is laiily simple, Lut cuiiently ieguiies a POSIX compliant opeiating
system. This means il you aie using Vinuows you will neeu to install Noue.js on eithei
oi a viitual machine iunning Linux oi some othei POSIX OS. Noue.js is availaLle liom
two piimaiy locations the http://nodcjs.org weL site oi the GithuL iepositoiy (http://
github.con/ry/nodc). The ollicial ieleases aie availaLle on the Noue weL site, this is
what you'll pioLaLly want to use. The latest cutting euge leatuies aie hosteu on GithuL
loi the coie uevelopment team, anu anyone else who wants a copy. Vhile these leatuies
aie new they aie also less staLle than those in a ielease.
Let's get staiteu Ly installing Noue.js on a Linux machine anu then we'll exploie some
othei opeiating systems. The liist thing to uo is uownloau Noue.js liom the weL site.
So let's go theie anu linu the latest ielease. Fiom the Noue homepage linu the uownloau
link:
The cuiient ielease at the time ol piint is 0.2.+ which is a staLle ielease. Let's uownloau
that with wget into oui home uiiectoiy:
Exanp|c 1-1. Gctting a copy oj thc Nodc sourcc
Enki:~/Downloads $ wget http://nodejs.org/dist/node-v0.2.4.tar.gz
--2010-10-31 15:16:49-- http://nodejs.org/dist/node-v0.2.4.tar.gz
Resolving nodejs.org (nodejs.org)... 8.12.44.238
Connecting to nodejs.org (nodejs.org)|8.12.44.238|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4002347 (3.8M) [application/octet-stream]
Saving to: node-v0.2.4.tar.gz
100%[======================================>] 4,002,347 603K/s in 6.7s
2010-10-31 15:16:56 (585 KB/s) - node-v0.2.4.tar.gz saved [4002347/4002347]
Enki:~/Downloads $
17

Noue.js veision numLeis lollow the C convention ol majoi.miui.minoi.
StaLle veisions ol Noue.js have an even miui veision numLei, uevelop-
ment veisions have an ouu miui veision numLei. It's uncleai when Noue
will stait using the veision numLeis, Lut it's a laii assumption that it
will only Le loi the liist "piouuction" ielease.
Once you have the coue you'll neeu to unpack it. The tai commanu uoes this using the
llags xzf. x stanus loi extiact (iathei than compiess), z tells tai to also uecompiess using
the GZIP algoiithm linally f inuicates we aie unpacking the lilename given as the linal
aigument:
Iigurc 1-1. Down|oading thc Nodc.js sourcc codc
18 | Chapter 4:Getting Started
Exanp|c 1-2. Unpac|ing thc codc
Enki:~/Downloads $ tar xzf node-v0.2.4.tar.gz
Enki:~/Downloads $ cd node-v0.2.4
Enki:~/Downloads/node-v0.2.4 $ ls
AUTHORS LICENSE README benchmark configure doc src tools
ChangeLog Makefile TODO bin deps lib test wscript
Enki:~/Downloads/node-v0.2.4 $

The next step is to conliguie the coue loi youi system. Noue.js uses the make system
loi its installation. The configure sciipt looks at youi system anu linus the paths Noue
neeus to use loi the uepenuancies it neeus. Noue geneially has veiy lew uepenuancies,
the installei ieguiies Python 2.+ oi gieatei, anu il you wish to use TLS oi ciyptology
(such as SHA1) Noue neeus the OpenSSL uevelopment liLiaiies. Running conliguie
will let you know il any ol these uepenuancies aie missing. I've incluueu some moie
specilic instiuctions loi a lew platloims in appcndix A il you've nevei uone this kinu ol
install Leloie.
Exanp|c 1-3. Conjiguring thc Nodc insta||
Enki:~/Downloads/node-v0.2.4 $ ./configure
Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
...
Checking for library rt : not found
Checking for function nanosleep : yes
Checking for function ceil : yes
Checking for fdatasync(2) with c++ : no
'configure' finished successfully (3.593s)
Enki:~/Downloads/node-v0.2.4 $

The next step to the installation is to make the pioject. This compiles Noue anu Luilus
the Linaiy veision ol the pioject that you will use into a Luilu uiiectoiy ol the souice
uiiectoiy we've Leen using. Noue numLeis each ol the Luilu steps it neeus to uo so you
can lollow the piogiess it makes uuiing the compile.
Exanp|c 1-1. Conpi|ing Nodc with thc na|c connand
Enki:~/Downloads/node-v0.2.4 $ make
Waf: Entering directory `/Users/croucher/Downloads/node-v0.2.4/build'
DEST_OS: darwin
DEST_CPU: x86
5.1 Installing Node.js | 19
Parallel Jobs: 1
[ 1/69] cc: deps/libeio/eio.c -> build/default/deps/libeio/eio_1.o
/usr/bin/gcc -rdynamic -D_GNU_SOURCE -DHAVE_CONFIG_H=1 -DEV_MULTIPLICITY=0 -pthread -g -O3 -DHAVE_OPENSSL=1 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_FDATASYNC=0 -DPLATFORM="darwin" -DNDEBUG -Idefault/deps/libeio -I../deps/libeio -Idefault -I.. ../deps/libeio/eio.c -c -o default/deps/libeio/eio_1.o
[ 2/69] cc: deps/libev/ev.c -> build/default/deps/libev/ev_1.o
/usr/bin/gcc -rdynamic -D_GNU_SOURCE -DHAVE_CONFIG_H=1 -DEV_MULTIPLICITY=0 -pthread -g -O3 -DHAVE_OPENSSL=1 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_FDATASYNC=0 -DPLATFORM="darwin" -DNDEBUG -Idefault/deps/libev -I../deps/libev -Idefault -I.. ../deps/libev/ev.c -c -o default/deps/libev/ev_1.o
[ 3/69] cc: deps/c-ares/ares_strcasecmp.c -> build/default/deps/c-ares/ares_strcasecmp_1.o
/usr/bin/gcc -rdynamic -D_GNU_SOURCE -DHAVE_CONFIG_H=1 -DEV_MULTIPLICITY=0 -pthread -g -O3 -DHAVE_OPENSSL=1 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_FDATASYNC=0 -DPLATFORM="darwin" -DNDEBUG -Idefault/deps/c-ares -I../deps/c-ares -Idefault/deps/c-ares/darwin-x86 -I../deps/c-ares/darwin-x86 ../deps/c-ares/ares_strcasecmp.c -c -o default/deps/c-ares/ares_strcasecmp_1.o
[ 4/69] cc: deps/c-ares/ares_free_string.c -> build/default/deps/c-ares/ares_free_string_1.o
/usr/bin/gcc -rdynamic -D_GNU_SOURCE -DHAVE_CONFIG_H=1 -DEV_MULTIPLICITY=0 -pthread -g -O3 -DHAVE_OPENSSL=1 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_FDATASYNC=0 -DPLATFORM="darwin" -DNDEBUG -Idefault/deps/c-ares -I../deps/c-ares -Idefault/deps/c-ares/darwin-x86 -I../deps/c-ares/darwin-x86 ../deps/c-ares/ares_free_string.c -c -o default/deps/c-ares/ares_free_string_1.o
...
[68/69] cxx: src/node_crypto.cc -> build/default/src/node_crypto_4.o
/usr/bin/g++ -DEV_MULTIPLICITY=0 -pthread -g -O3 -DHAVE_OPENSSL=1 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_FDATASYNC=0 -DPLATFORM="darwin" -DNDEBUG -Idefault/src -I../src -Idefault/deps/libeio -I../deps/libeio -Idefault/deps/http_parser -I../deps/http_parser -Idefault/deps/v8/include -I../deps/v8/include -Idefault/deps/libev -I../deps/libev -Idefault/deps/c-ares -I../deps/c-ares -Idefault/deps/c-ares/darwin-x86 -I../deps/c-ares/darwin-x86 -Ideps/v8/include ../src/node_crypto.cc -c -o default/src/node_crypto_4.o
[69/69] cxx_link: build/default/src/node_4.o build/default/src/node_buffer_4.o build/default/src/node_extensions_4.o build/default/src/node_http_parser_4.o build/default/src/node_net_4.o build/default/src/node_io_watcher_4.o build/default/src/node_child_process_4.o build/default/src/node_constants_4.o build/default/src/node_cares_4.o build/default/src/node_events_4.o build/default/src/node_file_4.o build/default/src/node_signal_watcher_4.o build/default/src/node_stat_watcher_4.o build/default/src/node_stdio_4.o build/default/src/node_timer_4.o build/default/src/node_script_4.o build/default/src/platform_darwin_4.o build/default/src/node_crypto_4.o build/default/deps/libeio/eio_1.o build/default/deps/http_parser/http_parser_2.o build/default/deps/libev/ev_1.o build/default/deps/c-ares/ares_strcasecmp_1.o build/default/deps/c-ares/ares_free_string_1.o build/default/deps/c-ares/ares_options_1.o build/default/deps/c-ares/ares_send_1.o build/default/deps/c-ares/ares_parse_txt_reply_1.o build/default/deps/c-ares/ares_parse_ptr_reply_1.o build/default/deps/c-ares/ares_nowarn_1.o build/default/deps/c-ares/ares_search_1.o build/default/deps/c-ares/ares_gethostbyname_1.o build/default/deps/c-ares/ares_getsock_1.o build/default/deps/c-ares/ares__timeval_1.o build/default/deps/c-ares/inet_ntop_1.o build/default/deps/c-ares/ares_parse_a_reply_1.o build/default/deps/c-ares/ares_getopt_1.o build/default/deps/c-ares/ares__close_sockets_1.o build/default/deps/c-ares/ares_expand_string_1.o build/default/deps/c-ares/ares_destroy_1.o build/default/deps/c-ares/ares_cancel_1.o build/default/deps/c-ares/ares_parse_aaaa_reply_1.o build/default/deps/c-ares/ares_parse_ns_reply_1.o build/default/deps/c-ares/ares_version_1.o build/default/deps/c-ares/ares__get_hostent_1.o build/default/deps/c-ares/ares_writev_1.o build/default/deps/c-ares/ares_expand_name_1.o build/default/deps/c-ares/ares_free_hostent_1.o build/default/deps/c-ares/ares_parse_mx_reply_1.o build/default/deps/c-ares/ares_gethostbyaddr_1.o build/default/deps/c-ares/ares_query_1.o build/default/deps/c-ares/ares_data_1.o build/default/deps/c-ares/ares_init_1.o build/default/deps/c-ares/ares_fds_1.o build/default/deps/c-ares/inet_net_pton_1.o build/default/deps/c-ares/ares_strerror_1.o build/default/deps/c-ares/bitncmp_1.o build/default/deps/c-ares/ares_getnameinfo_1.o build/default/deps/c-ares/ares_library_init_1.o build/default/deps/c-ares/ares_mkquery_1.o build/default/deps/c-ares/ares_process_1.o build/default/deps/c-ares/windows_port_1.o build/default/deps/c-ares/ares_parse_srv_reply_1.o build/default/deps/c-ares/ares_llist_1.o build/default/deps/c-ares/ares_timeout_1.o build/default/deps/c-ares/ares__read_line_1.o build/default/deps/c-ares/ares_strdup_1.o -> build/default/node
/usr/bin/g++ default/src/node_4.o default/src/node_buffer_4.o default/src/node_extensions_4.o default/src/node_http_parser_4.o default/src/node_net_4.o default/src/node_io_watcher_4.o default/src/node_child_process_4.o default/src/node_constants_4.o default/src/node_cares_4.o default/src/node_events_4.o default/src/node_file_4.o default/src/node_signal_watcher_4.o default/src/node_stat_watcher_4.o default/src/node_stdio_4.o default/src/node_timer_4.o default/src/node_script_4.o default/src/platform_darwin_4.o default/src/node_crypto_4.o default/deps/libeio/eio_1.o default/deps/http_parser/http_parser_2.o default/deps/libev/ev_1.o default/deps/c-ares/ares_strcasecmp_1.o default/deps/c-ares/ares_free_string_1.o default/deps/c-ares/ares_options_1.o default/deps/c-ares/ares_send_1.o default/deps/c-ares/ares_parse_txt_reply_1.o default/deps/c-ares/ares_parse_ptr_reply_1.o default/deps/c-ares/ares_nowarn_1.o default/deps/c-ares/ares_search_1.o default/deps/c-ares/ares_gethostbyname_1.o default/deps/c-ares/ares_getsock_1.o default/deps/c-ares/ares__timeval_1.o default/deps/c-ares/inet_ntop_1.o default/deps/c-ares/ares_parse_a_reply_1.o default/deps/c-ares/ares_getopt_1.o default/deps/c-ares/ares__close_sockets_1.o default/deps/c-ares/ares_expand_string_1.o default/deps/c-ares/ares_destroy_1.o default/deps/c-ares/ares_cancel_1.o default/deps/c-ares/ares_parse_aaaa_reply_1.o default/deps/c-ares/ares_parse_ns_reply_1.o default/deps/c-ares/ares_version_1.o default/deps/c-ares/ares__get_hostent_1.o default/deps/c-ares/ares_writev_1.o default/deps/c-ares/ares_expand_name_1.o default/deps/c-ares/ares_free_hostent_1.o default/deps/c-ares/ares_parse_mx_reply_1.o default/deps/c-ares/ares_gethostbyaddr_1.o default/deps/c-ares/ares_query_1.o default/deps/c-ares/ares_data_1.o default/deps/c-ares/ares_init_1.o default/deps/c-ares/ares_fds_1.o default/deps/c-ares/inet_net_pton_1.o default/deps/c-ares/ares_strerror_1.o default/deps/c-ares/bitncmp_1.o default/deps/c-ares/ares_getnameinfo_1.o default/deps/c-ares/ares_library_init_1.o default/deps/c-ares/ares_mkquery_1.o default/deps/c-ares/ares_process_1.o default/deps/c-ares/windows_port_1.o default/deps/c-ares/ares_parse_srv_reply_1.o default/deps/c-ares/ares_llist_1.o default/deps/c-ares/ares_timeout_1.o default/deps/c-ares/ares__read_line_1.o default/deps/c-ares/ares_strdup_1.o -o /Users/croucher/Downloads/node-v0.2.4/build/default/node -pthread -framework Carbon -rdynamic /Users/croucher/Downloads/node-v0.2.4/build/default/libv8.a -lssl -lcrypto -ldl
Waf: Leaving directory `/Users/croucher/Downloads/node-v0.2.4/build'
'build' finished successfully (3m8.885s)
Enki:~/Downloads/node-v0.2.4 $

The linal step is to use make to install Noue. Fiist I'm going to show how to install Noue
gloLally loi the whole system. This ieguiies you to have access to eithei the root usei
oi sudo piivileges to uo things as root.
Exanp|c 1-5. |nsta||ing Nodc jor thc who|c systcn
Enki:~/Downloads/node-v0.2.4 $ sudo make install
Password:
Waf: Entering directory `/Users/croucher/Downloads/node-v0.2.4/build'
DEST_OS: darwin
DEST_CPU: x86
Parallel Jobs: 1
* installing deps/libeio/eio.h as /usr/local/include/node/eio.h
* installing deps/v8/include/v8-debug.h as /usr/local/include/node/v8-debug.h
...
* installing build/default/node as /usr/local/bin/node
* installing build/default/src/node_config.h as /usr/local/include/node/node_config.h
Waf: Leaving directory `/Users/croucher/Downloads/node-v0.2.4/build'
'install' finished successfully (1.338s)
Enki:~/Downloads/node-v0.2.4 $

Il you want to install only loi the local usei, anu avoiu using the sudo commanu then
you neeu to iun the configure sciipt with the --prefix aigument in to tell Noue to
install somewheie othei than the uelault.
20 | Chapter 4:Getting Started
Exanp|c 1-. |nsta||ing Nodc jor a |oca| uscr
Enki:~/Downloads/node-v0.2.4 $ mkdir ~/local
Enki:~/Downloads/node-v0.2.4 $ ./configure --prefix=~/local
Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
...
Checking for function nanosleep : yes
Checking for function ceil : yes
Checking for fdatasync(2) with c++ : no
'configure' finished successfully (3.248s)
Enki:~/Downloads/node-v0.2.4 $ make
Waf: Entering directory `/Users/croucher/Downloads/node-v0.2.4/build'
DEST_OS: darwin
DEST_CPU: x86
Parallel Jobs: 1
...
Waf: Leaving directory `/Users/croucher/Downloads/node-v0.2.4/build'
'build' finished successfully (5.943s)
Enki:~/Downloads/node-v0.2.4 $ make install
Waf: Entering directory `/Users/croucher/Downloads/node-v0.2.4/build'
DEST_OS: darwin
DEST_CPU: x86
Parallel Jobs: 1
* installing deps/libeio/eio.h as /Users/croucher/local/include/node/eio.h
* installing deps/v8/include/v8-debug.h as /Users/croucher/local/include/node/v8-debug.h
...
* installing build/default/node as /Users/croucher/local/bin/node
* installing build/default/src/node_config.h as /Users/croucher/local/include/node/node_config.h
Waf: Leaving directory `/Users/croucher/Downloads/node-v0.2.4/build'
'install' finished successfully (0.253s)
Enki:~/Downloads/node-v0.2.4 $ cd ~/local
Enki:~/local $ ls
bin include lib share
Enki:~/local $ cd bin
Enki:~/local/bin $ ls
node node-repl node-waf
Enki:~/local/bin $

5.1 Installing Node.js | 21
5.2 First steps in code
5.2.1 Node REPL
One ol the things that's olten haiu to explain aLout Noue.js is that while it's a seivei
it's also simply a iuntime enviionment in the same way that Peil, Python anu RuLy aie.
As such while we olten ielei to Noue.js as "seivei-siue ]avaSciipt" it isn't ieally an
accuiate uesciiption ol what Noue.js uoes. One ol the Lest way to get to giips with
Noue.js is to use Noue REPL (Reau-Eval-Piint-Loop). Noue REPL is an inteiactive
Noue.js piogiamming enviionment. It's gieat loi testing out anu leaining aLout
Noue.js. Il you want tiy out any ol the snippets in this Look you can uo it in Noue
REPL. Moie than that Lecause Noue is a wiappei aiounu VS, Noue REPL is an iueal
place to easily tiy out ]avaSciipt.
Let's launch Noue REPL anu tiy out a lew Lits ol ]avaSciipt to waim up. Open up a
console on youi system, the system I'm using is a Mac with a custom commanu piompt
so youi system might look a little Lit uilleient Lut the commanus shoulu Le the same:
Exanp|c 1-7. Starting Nodc REPL and trying sonc javaScript
$Enki:~ $ node
> 3 > 2 > 1
false
> true == 1
true
> true === 1
false

3 > 2 > 1 //false is liom http://wtljs.com a collection ol weiiu anu
amusing things aLout ]avaSciipt. Il you want to see moie weiiu things
aLout ]avaSciipt liom wtljs with explanations see appenuix B.
Having a live piogiamming enviionment is a ieally gieat leaining tool Lut theie aie also
a lew helplul leatuies ol Noue's REPL you shoulu know aLout to make the most ol
that. The meta-commanus in Noue REPL aie accesseu with a . Leloie the com-
manu. .help shows the help menu, .clear cleais the cuiient context anu .exit guits
Noue REPL. The most uselul commanu is .clear. .clear cleais the cuiient execution
context. This means that any vaiiaLles oi closuies you have in memoiy aie cleaieu
without iestaiting the REPL.
Exanp|c 1-8. Using thc ncta-jcaturcs in Nodc REPL
> console.log('Hello World');
22 | Chapter 4:Getting Started
Hello World
> .help
.clear Break, and also clear the local context.
.exit Exit the prompt
.help Show repl options
> .clear
Clearing context...
> .exit
Enki:~ $

Vhen using a REPL simply typing the name ol a vaiiaLle will enumeiate it in the shell.
Noue tiies to uo this intelligently so a complex oLject won't just Le iepiesenteu as
simple Object Lut actually in a uesciiptive way which iellects what's in the oLject. The
main exception to this is lunctions. It's not that REPL uoesn't have a way to enumeiate
lunctions, it's that lunctions have the tenuency to Le veiy laige. Il REPL enumeiateu
lunctions then the output coulu easily Le extiemely laige.
Exanp|c 1-9. Sctting and cnuncrating objccts with REPL
Enki:~ $ node
> myObj = {};
{}
> myObj.list = ["a", "b", "c"];
[ 'a', 'b', 'c' ]
> myObj.doThat = function(first, second, third) { console.log(first); };
[Function]
> myObj
{ list: [ 'a', 'b', 'c' ]
, doThat: [Function]
}
>

5.2.2 My First Server
Vhile REPL gives us a gieat tool loi leaining anu expeiimentation the main application
ol Noue.js is as a seivei. One ol the specilic uesign goals ol Noue.js is to pioviue a
highly scalaLle seivei enviionment. This is an aiea wheie Noue uilleis liom VS. Vhile
the VS iuntime is useu to inteipiet the ]avaSciipt Noue uses a numLei ol specilic li-
Liaiies that aie highly optimizeu loi seivei application. In paiticulai the HTTP mouule
was wiitten liom sciatch in C to pioviue a veiy last non-Llocking implementation ol
HTTP. Let's take a look at the canonical Noue "Hello Voilu" example using an HTTP
seivei.
5.2 First steps in code | 23
Exanp|c 1-10. A Hc||o Wor|d Nodc.js Wcb Scrvcr
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');


The liist thing that this coue uoes is use require to incluue the HTTP liLiaiy into the
piogiam. This concept is useu in many languages, Lut Noue uses the Common]S mou-
ule loimat which we'll talk aLout moie latei in the chaptei. The main thing to know at
this point is that the lunctionality in the HTTP liLiaiy is now assigneu to the http oLject.
Next we neeu an HTTP seivei. Unlike some languages, like PHP which iun insiue a
seivei such as Apache, Noue itsell acts as the VeL seivei. Howevei, that also means
we have to cieate it. The next line calls a lactoiy methou liom the HTTP mouule which
cieates new HTTP seiveis. The new HTTP seivei isn't assigneu to a vaiiaLle, it's simply
going to Le an anonymous oLject in the gloLal scope. Insteau we use chaining to initi-
alize the seivei anu tell it to listen on poit 8124. Vhen calling the createServer methou
we pass an aigument. This is an essential concept in Noue.
Vhen calling createServer we passeu a lunction to the methou. This methou is at-
tacheu to the new seivei's event listenei loi the request event. Events aie cential to Loth
]avaSciipt anu Noue. In this case whenevei theie is a new ieguest to the VeL seivei
this the methou that will get calleu to ueal with the ieguest. Ve call these kinus ol
methous ca||bac|s. That's Lecause whenevei an event happens we "call Lack" all the
methous listening loi that event. Peihaps a goou analogy woulu Le oiueiing a Look
liom a Lookshop. Vhen youi Look is in stock they ca|| bac| to let you know you can
come anu collect it. This specilic callLack takes the aiguments req loi the ieguest oLject
anu res loi the iesponse oLject.
Insiue the lunction we cieateu loi the callLack we call a couple ol methous on the
res oLject. These calls mouily the iesponse. In this example we uon't use the ieguest,
Lut typically you woulu use Loth the ieguest anu iesponse oLjects. The liist thing we
uo is set the HTTP iesponse heauei. Ve can't senu any actual iesponse to the
client without it. the res.writeHead methou uoes this. Ve set the values 200 (loi the
HTTP status coue 200 OK) anu pass a list ol HTTP heaueis. In this case the only we
specily is the Content-type heauei. Once we've wiitten the HTTP heauei to the client
we can wiite the HTTP Louy. In this case we Loth wiite the Louy anu close the con-
nection with the same methou. The end methou closes the HTTP connection, Lut since
we also passeu it a stiing it will senu that to the client Leloie it closes the connection.
Finally, the last line ol oui example uses the console.log. This simply piints to
STDOUT much like it's Liowsei countei-pait as suppoiteu Ly FiieLug anu VeL Inspectoi.
24 | Chapter 4:Getting Started
Let's iun this with Noue.js on the console anu see what we get:
Exanp|c 1-11. Running thc Hc||o Wor|d cxanp|c
Enki:~ $ node
node> var http = require('http');
node> http.createServer(function (req, res) {
... res.writeHead(200, {'Content-Type': 'text/plain'});
... res.end('Hello World\n');
... }).listen(8124, "127.0.0.1");
node> console.log('Server running at http://127.0.0.1:8124/');
Server running at http://127.0.0.1:8124/
node>

In listing 5.2.3 I stait a Noue REPL anu type in the coue liom the sample (I'll loigive
you loi pasting liom the weL site). Noue REPL accepts the coue using ... to inuicate
paits ol the coue that aien't completeu statements. Vhen we iun the console.log line
Noue REPL piints out Server running at http://127.0.0.1:8124/. Now we aie ieauy
to call oui Hello Voilu example in a weL Liowsei.
Iigurc 1-2. \icwing thc Hc||o Wor|d Wcb Scrvcr jron a browscr
5.2 First steps in code | 25
It woiks! Vhile this isn't exactly a stunning uemo, it is notaLle that we got hello woilu
woiking in 6 lines ol coue. Not that I woulu iecommenu that style ol couing, Lut we
aie staiting to get some wheie.
26 | Chapter 4:Getting Started

You might also like