node for beginner

10
8/11/2019 Node for Beginner http://slidepdf.com/reader/full/node-for-beginner 1/10 Node.js for Beginners by Maciej Sopyło17 Aug 2012113 Comments 6016 Event-driven programming can be overwhelming for beginners, which can make Node.js difficlt to get started with. !t don"t let that discorage yo# $n this article, $ will teach yo some of the basics of Node.js and e%plain why it has become so poplar. Introduction &o start sing Node.js, yo mst first nderstand the differences between Node.js and traditional server-side scripting environments 'eg( )*), )ython, +by, etc. Asynchronous Programming Node.js uses a module architecture to simplify the creation of complex applications. hances are good that yo are familiar with asynchronos programming# it is, after all, the / in /ja%. Every fnction in Node.js is asynchronos. &herefore, everything that wold normally block the thread is instead e%ected in the backgrond. &his is the most important thing to remember abot Node.js. 0or e%ample, if yo are reading a file on the file system, yo have to specify a callback fnction that is e%ected when the read operation has completed.  You are Doing Everything! Node.js is only an environment - meaning that yo have to do everything yorself. &here is not a defalt *&&) server, or any server for that matter. &his can be overwhelming for new sers, bt the payoff is a high performing web app. 1ne script handles all commnication with the clients. &his considerably redces the nmber of resorces sed by the application. 0or e%ample, here is the code for a simple Node.js application( 01 02 03 04 05 06 07 08 09 10 11 var i, a, b, c, max;  max = 1000000000;  var d = Date.now();  for (i = 0; i < max; i++) {  a = 1234 + !"# + i;  b = 1234 $ !"# + i;  c = 1234 % 2 + i; &  

Upload: chera-robinson

Post on 02-Jun-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 1/10

Node.js for Beginnersby Maciej Sopyło17 Aug 2012113 Comments

6016

Event-driven programming can be overwhelming for beginners, which can make Node.js difficlt to get

started with. !t don"t let that discorage yo# $n this article, $ will teach yo some of the basics of

Node.js and e%plain why it has become so poplar.

Introduction

&o start sing Node.js, yo mst first nderstand the differences between Node.js and traditional

server-side scripting environments 'eg( )*), )ython, +by, etc.

Asynchronous Programming

Node.js uses a module architecture to simplify the creation ofcomplex applications.

hances are good that yo are familiar with asynchronos programming# it is, after all, the / in /ja%.

Every fnction in Node.js is asynchronos. &herefore, everything that wold normally block the thread

is instead e%ected in the backgrond. &his is the most important thing to remember abot Node.js.

0or e%ample, if yo are reading a file on the file system, yo have to specify a callback fnction that is

e%ected when the read operation has completed.

 You are Doing Everything!Node.js is only an environment - meaning that yo have to do everything yorself. &here is not a

defalt *&&) server, or any server for that matter. &his can be overwhelming for new sers, bt the

payoff is a high performing web app. 1ne script handles all commnication with the clients. &his

considerably redces the nmber of resorces sed by the application. 0or e%ample, here is the code

for a simple Node.js application(

01

02

03

04

05

06

07

08

09

10

11

var i, a, b, c, max;

 

max = 1000000000;

 var d = Date.now();

 

for (i = 0; i < max; i++) {  a = 1234 + !"# + i;  b = 1234 $ !"# + i;  c = 1234 % 2 + i;&

 

Page 2: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 2/10

12

13con'oe.o(Date.now() * d);

 /nd here is the e2ivalent written in )*)(

01

0203

04

05

06

07

08

09

10

11

12

1314

15

a = n;b = n;c = n;i = n;max = 1000000000;

 

'tart = microtime(tre);

 

for (i = 0; i < max; i++) {  a = 1234 + !"# + i;  b = 1234 $ !"# + i;  c = 1234 % 2 + i;&

 var-dm(microtime(tre) * 'tart);

Now let"s look at the benchmark nmbers. &he following table lists the response times, in milliseconds,

for these two simple applications(

Number of iterations Node.js PHP

344 5.44 4.36

34"444 7.44 34.87

3"444"444 38.44 3339.56

34"444"444 367.44 34:53.6:

3"444"444"444 3333;.44 347:5<5.39

$ e%ected the two apps from the command line so that no server wold delay the apps" e%ection. $

ran each test ten times and averaged the reslts. )*) is notably faster with a smaller amont of

iterations, bt that advantage 2ickly dissolves as the nmber of iterations increases. =hen all is said

and done, )*) is 97> slower than Node.js?

Node.js is fast, bt yo will need to learn a few things in order to se it properly.

odues

Node.js ses a modle architectre to simplify the creation of comple% applications. Modles are akin

to libraries in , or nits in )ascal. Each modle contains a set of fnctions related to the sbject of

Page 3: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 3/10

the modle. 0or e%ample, the http modle contains fnctions specific to *&&). Node.js provides a few

core modles ot of the bo% to help yo access files on the file system, create *&&) and &)@AB)

servers, and perform other sefl fnctions.

$nclding a modle is easy# simply call the re/ire() fnction, like this(

1 var tt = re/ire(tt);

Node.js is only an environment; you have to do everythingyourself.

&he re/ire() fnction retrns the reference to the specified modle. $n the case of this code, a

reference to the http modle is stored in the tt variable.

$n the above code, we passed the name of a modle to the re/ire() fnction. &his cases Node to

search for a node_modules folder in or application"s directory, and search for the http modle in thatfolder. $f Node does not find the node_modules folder 'or the http modle within it, it then looks

throgh the global modle cache. Co can also specify an actal file by passing a relative or absolte

path, like so(

1 var mode = re/ire(.%mode.');

Modles are encapslated pieces of code. &he code within a modle is mostly private - meaning that

the fnctions and variables defined within them are only accessible from the inside of the modle. Co

can, however, e%pose fnctions and@or variables to be sed otside of the modle. &o do so, se

the exort' object and poplate its properties and methods with the pieces of code that yo want to

e%pose. onsider the following modle as an e%ample(

1

2

3

4

5

6

7

8

9

var 56 = at.56;

 

exort'.area = fnction (r) {  retrn 56 $ r $ r;&;

 

exort'.circmference = fnction (r) {  retrn 2 $ 56 $ r;&;

&his code creates a 56 variable that can only be accessed by code contained within the modle# it is

not accessible otside of the modle. Ne%t, two fnctions are created on the exort' object. &hese

fnctions are accessible otside of the modle becase they are defined on the exort' object. /s a

reslt, 56 is completely protected from otside interference. &herefore, yo can rest assred

that area() andcircmference() will always behave as they shold 'as long as a vale is spplied

for the r parameter.

Page 4: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 4/10

"oba #co$e

Node is a DavaScript environment rnning in oogle"s F; DavaScript engine. /s sch, we shold

follow the best practices that we se for client-side development. 0or e%ample, we shold avoid ptting

anything into the global scope. &hat, however, is not always possible. &he global scope in Node

is 789:8 'as opposed to window in the browser, and yo can easily create a global variable of

fnction by omitting the varkeyword, like this(

1

2

obaariabe = 1;obanction = fnction () { ... &;

1nce again, globals shold be avoided whenever possible. So be carefl and remember to

se var when declaring a variable.

Instaation

Natrally, we need to install Node before we can write and e%ecte an app. $nstallation is straight

forward, if yo se =indows or 1S G# the nodejs.org website offers installers for those operating

systems. 0or Hin%, se any package manager. 1pen p yor terminal and type(

1

2

'do at*et date'do at*et in'ta node

or(

1

2

'do atitde date'do atitde in'ta node

Node.js is in sid repositories# yo may need to add them to yor sorces list(

1'do eco deb tt>%%ft.'.debian.or%debian% 'id main ?%etc%at%'orce'.i't.d%'id.i't

!t be aware that installing sid packages on older systems may break yor system. !e carefl, and

remove %etc%at%'orce'.i't.d%'id.i't after yo finish installing Node.

Instaing Ne% odues

Node.js has a package manager, called Node )ackage Manager 'N)M. $t is atomatically installed

with Node.js, and yo se N)M to install new modles. &o install a modle, open yor

terminal@command line, navigate to the desired folder, and e%ecte the following command(

1 nm in'ta mode-name

Page 5: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 5/10

$t doesn"t matter what 1S yo have# the above command will install the modle yo specify in place

of module_name.

&he Heo 'ord A$$

Natrally, or first Node.js script will print the te%t @eo AordB to the console. reate a file,

called hello.js, and type the following code(

1 con'oe.o(@eo AordB);

Now let"s e%ecte the script. 1pen the terminal@command line, navigate to the folder that

contains hello.js, and e%ecte the following command(

1 node eo.'

Co shold see @eo AordB displayed in the console.

H&&P #erver 

Het"s move on to a more advanced application# it"s not as complicated as yo may think. Hets start with

the following code. +ead the comments and then the e%planation below(

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

%% 6ncde tt mode.var tt = re/ire(CttC);

 

%% reate te 'erver. nction a''ed a' arameter i' caed on everre/e't made.%% re/e't variabe od' a re/e't arameter'%% re'on'e variabe aow' o to do antin wit re'on'e 'ent tote cient.tt.createEerver(fnction (re/e't, re'on'e) {  %% ttac i'tener on end event.  %% Fi' event i' caed wen cient 'ent a data and i' waitinfor re'on'e.  re/e't.on(CendC, fnction () {  %% Arite eader' to te re'on'e.  %% 200 i' @FF5 'tat' code (ti' one mean' 'cce'')  %% Eecond arameter od' eader fied' in obect

  %% Ae are 'endin ain text, 'o ontent*Fe 'od betext%ain  re'on'e.write@ead(200, {  ontent*Fe> text%ain  &);  %% Eend data and end re'on'e.  re'on'e.end(@eo @FF5B);  &);%% 8i'ten on te #0#0 ort.&).i'ten(#0#0);

Page 6: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 6/10

Page 7: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 7/10

)eading and 'riting +ies

&o manage files in Node, we se the fs modle 'a core modle. =e read and write files sing

the f'.readie() and f'.writeie() methods, respectively. $ will e%plain the argments after the

following code(

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

%% 6ncde tt mode,var tt = re/ire(CttC),%% nd m'/ mode ove 't in'taed.  f' = re/ire(Cf'C);

 

%% reate te tt 'erver.tt.createEerver(fnction (re/e't, re'on'e) {  %% ttac i'tener on end event.  re/e't.on(CendC, fnction () {  %% Jead te fie.

  f'.readie(Cte't.txtC, tf*#, fnction (error,data) {  %% Arite eader'.  re'on'e.write@ead(200, {  ontent*Fe> text%ain  &);  %% 6ncrement te nmber obtained from fie.  data = ar'e6nt(data) + 1;  %% Arite incremented nmber to fie.  f'.writeie(te't.txt, data);  %% Knd re'on'e wit 'ome nice me''ae.  re'on'e.end(Fi' ae wa' refre'ed + data + time'B);

  &);  &);%% 8i'ten on te #0#0 ort.&).i'ten(#0#0);

Node.js has a package manager, called Node PackageManager (NPM. !t is automatically installed "ith Node.js

Save this as files.js. !efore yo rn this script, create a file named test.txt  in the same directory

as files.js.

&his code demonstrates the f'.readie() and f'.writeie() methods. Every time the server

receives a re2est, the script reads a nmber from the file, increments the nmber, and writes the new

nmber to the file. &he f'.readie() method accepts three argments( the name of file to read, the

e%pected encoding, and the callback fnction.

Page 8: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 8/10

=riting to the file, at least in this case, is mch more simple. =e don"t need to wait for any reslts,

althogh yo wold check for errors in a real application. &hef'.writeie() method accepts the file

name and data as argments. $t also accepts third and forth argments 'both are optional to specify

the encoding and callback fnction, respectively.

Now, let"s rn this script with the following command(

1 node fie'.'

1pen it in browser 'tt>%%ocao't>#0#0 and refresh it a few times. Now, yo may think that

there is an error in the code becase it seems to increment by two. &his isn"t an error. Every time yo

re2est this A+H, two re2ests are sent to the server. &he first re2est is atomatically made by the

browser, which re2ests favicon.ico, and of corse, the second re2est is for the A+H

'tt>%%ocao't>#0#0.

Even thogh this behavior is technically not an error, it is behavior that we do not want. =e can fi% this

easily by checking the re2est A+H. *ere is the revised code(

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

%% 6ncde tt mode,var tt = re/ire(CttC),%% nd m'/ mode ove 't in'taed.  f' = re/ire(Cf'C);

 

%% reate te tt 'erver.tt.createEerver(fnction (re/e't, re'on'e) {  %% ttac i'tener on end event.  re/e't.on(end, fnction () {  %% ecL if 'er re/e't' %

  if (re/e't.r == %) {  %% Jead te fie.  f'.readie(te't.txt, tf*#, fnction (error,data) {  %% Arite eader'.  re'on'e.write@ead(200, {  ontent*Fe> text%ain  &);  %% 6ncrement te nmber obtained from fie.  data = ar'e6nt(data) + 1;  %% Arite incremented nmber to fie.  f'.writeie(te't.txt, data);  %% Knd re'on'e wit 'ome nice me''ae.  re'on'e.end(Fi' ae wa' refre'ed + data+  time'B);  &);  & e'e {  %% 6ndicate tat re/e'ted fie wa' not fond.  re'on'e.write@ead(404);  %% nd end re/e't witot 'endin an data.  re'on'e.end();  &  &);

Page 9: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 9/10

28

29

30

31

32

33

%% 8i'ten on te #0#0 ort.&).i'ten(#0#0);

&est it now# it shold work as e%pected.

 /dvertisement

Accessing y#,* Databases

Most traditional server-side technologies have a bilt-in means of connecting to and 2erying a

database. =ith Node.js, yo have to install a library. 0or this ttorial, $"ve picked the stable and easy to

se node#mys$l . &he fll name of this modle ismys$l%&.'.'#alpha&  'everything after the I is the

version nmber. 1pen yor console, navigate to the directory where yo"ve stored yor scripts, and

e%ecte the following command(

1 nm in'ta m'/M2.0.0*aa2

&his downloads and installs the modle, and it also creates the node_modules folder in the crrent

directory. Now let"s look at how we can se this in or code# see the following e%ample(

01

02

0304

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

%% 6ncde tt mode,var tt = re/ire(tt),%% nd m'/ mode ove 't in'taed.

m'/ = re/ire(Cm'/C);

%% reate te connection.%% Data i' defat to new m'/ in'taation and 'od be caned accordin or confiration.var connection = m'/.createonnection({

'er> CrootC,a''word> CC,databa'e> Cdb-nameC

&);

%% reate te tt 'erver.tt.createEerver(fnction (re/e't, re'on'e) {

%% ttac i'tener on end event.re/e't.on(end, fnction () {

%% Ner te databa'e.connection./er(EK8KF $ J9 or-tabe;, fnction (error, row',

fied') {re'on'e.write@ead(200, {

ontent*Fe> x*aication%'on&);%% Eend data a' OE9P 'trin.

Page 10: Node for Beginner

8/11/2019 Node for Beginner

http://slidepdf.com/reader/full/node-for-beginner 10/10

22

23

24

25

26

27

28

29

  %% Jow' variabe od' te re't of te /er.re'on'e.end(OE9P.'trinif(row'));

&);&);

%% 8i'ten on te #0#0 ort.

&).i'ten(#0#0);

Jerying the database with this library is easy# simply enter the 2ery string and callback fnction. $n a

real application, yo shold check if there were errors 'the errorparameter will not be ndefined if

errors occrred and send response codes dependent pon the sccess or failre of the 2ery. /lso

note that we have set theontent*Fe to x*aication%'on, which is the valid M$ME type for

DS1N. &herow' parameter contains the reslt of the 2ery, and we simply convert the data inrow' to a

DS1N strctre sing the OE9P.'trinif() method.

Save this file as mys$l.js, and e%ecte it 'if yo have MySJH installed, that is(

1 node m'/.'

Navigate to tt>%%ocao't>#0#0 in yor browser, and yo shold be prompted to download the

DS1N-formatted file.

-oncusion

very function in Node.js is asynchronous.

Node.js re2ires e%tra work, bt the payoff of a fast and robst application is worth it. $f yo don"t want

to do everything on the lowest level, yo can always pick some framework, sch as KE%press, to make

it easier to develop applications.

Node.js is a promising technology and an e%cellent choice for a high load application. $t has been

proven by corporations, like Microsoft, e!ay, and Cahoo. $f yo"re nsre abot hosting yor

website@application, yo can always se a cheap F)S soltion or varios clod-based services, sch

as Microsoft /Lre and /maLon E5. !oth of these services provide scalable environments at a

reasonable price.