15

Node js by example

Embed Size (px)

Citation preview

1. Introductioni. About

2. Node.jsCorei. Assertii. Buffer

i. Bits&Bytes

TableofContents

ThisBookisavailablefreeonlineat:http://nelsonic.gitbooks.io/node-js-by-example/inMOBI(Kindle),PDF(everything)andePUB(iBooks).

Acomputerwithinternetaccess

Time:30h(e.g.2months30minsperdayor1weekintensive)

Node.jsletsyoueasilybuildnetworkedsoftware(websites,applications"apps"usingJavaScript).

Node.jsisnot"point-and-click"likeWordPress,SquareSpaceorSalesforce.com;youwillneedtowritesome"code".ButasIwilldemonstrate,that'saloteasierthanitsounds(ifyou'renewtowritingcode),givesyoumorepower/flexibilityandputsyouinfullcontrol.

Ifyouhaveneverwrittenanycodeofanysortbefore,Irecommendyoustartingwith:http://gitbookio.gitbooks.io/javascript/YouneedtohaveJavaScriptbasicstomakethemostofNode.js

Yes!Someofthebiggestorganisations/companiesintheworldareusingNode.jsinProductionsystems.

Alibaba,Ajax.org,Box.com,BritishSkyBroadcasting(Sky/NowTV),CNN,Cloudup,CondeNast,DirectTV,DowJones,eBay,Etsy,FeedHenry,GitHub,Google,Groupon,HBO,Help.com,HP,iTV,Joyent(duh!),Klout,LinkedIn,McDonalds,Medium,Mozilla,NetFlix,OpenTable,PayPal,Pearson,Q,Revolt,Square,Tesco,ThomasCook,Trello,Uber,Voxer,Walmart,Wikimedia(inprogressofmovingtoSOAwithnode!)Yahoo,Yammer,Yandex,Zendesk

LearnNode.jsbyExample

Requirements

WhatisNode.js?

FrequentlyAskedQuestions(FAQ)

Q:IamNewtoProgrammingShouldIStartwithNode.js?

Q:Node.jsisnot"Version1.0"yetcanweuseditinProduction?

AShortListofCompaniesusingNode.js

Wantmore?See:http://nodejs.org/industry/andhttps://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node

http://nodejs.org/download/

Thenode.js("core")hasmanyusefulmodules.

Bookmark:http://nodejs.org/api(youwillcomebacktoit)

Whichnode.jscorepackage(s)can/shouldIuse?

Everycoremodulehasa"StabilityIndex"ratingonthenode.jsAPI.

Generalrule:Ifyouarebeingpaidtowritecodethatrunsinnode.js,pickcoremodules/methodswithstabilityStable,APIFrozenandLocked.

Tryit!

Download&Install

Node.js(Core)API

Stability(Canweuseit?)

clusterisExperimental-don'tusedomainisUnstable-don'tusepathisStable-useeventsisFrozen-useassertisLocked-use

CoreModulestoLearn

pathos

CommunityModulestoLearn:

jscs-codestylecheckerq-promiseslibrarynd-viewdocumentationforamodule

Examples

Thisbookisforeveryonewhowantstolearnnode.jsbutdoesn'tknowwheretostart.

About

Thenode.js("core")hasmanyusefulmodules.

Bookmark:http://nodejs.org/api(youwillcomebacktoit)

WearegoingtocoverthemoduleslabeledStability:Stable,APIFrozenandLocked.OnlyusetheExperimentalorUnstablecoremoduleswhenyouwanttotrythelatest&greatestandatyourownrisk;avoidusingthemonaprojectforaclient(unlessyougetagreementinwritingthattheywanttosailclosetothewindforaspecificuserfeature).

Node.js(Core)API

Node.jsinstalledNopriorknowledge

Basic/Beginner

Assert-verb-stateafactorbeliefconfidentlyandforcefully.(dictionarydefinition)

Whenwritingcodewewriteteststoautomaticallycheckourcodeisworkingasweexpectitto.

Assertisthemostrudimentarywayofwritingtests.Itprovidesnofeedbackwhenrunningyourtestsunlessonefails.

Theassertmodulehas11methodsbutyouwillonly(regularly)useafewofthem:assert.equal,assert.deepEqualandassert.throws.Eachareexplainedwithexamplesbelow.

Thefirstmethod(alphabetically),buttheleastusefulforpracticalpurposes(unlessyouexpectamethod/testtoalwaysfail).

Throwsanexceptionthatdisplaysthevaluesforactualandexpectedseparatedbytheprovidedoperator.

Example:

assert.fail(21,42,'TestFailed','###')

Output:

thrownewassert.AssertionError({

^

AssertionError:Faild

atObject.<anonymous>(assert.js:2:8)

atModule._compile(module.js:456:26)

atObject.Module._extensions..js(module.js:474:10)

atModule.load(module.js:356:32)

atFunction.Module._load(module.js:312:12)

atFunction.Module.runMain(module.js:497:10)

atstartup(node.js:119:16)

atnode.js:906:3

Usefulness:virtuallynone.Ihaven'tfoundapracticaluseforthis.http://nodejs.org/api/assert.html#assert_assert_fail_actual_expected_message_operator

Testsifvalueis"truthy",itisequivalentto:

Assertletsyoutestyourcode

Prerequisites

SkillLevel

What?

assert.fail(actual,expected,message,operator)

assert(value,message),assert.ok(value,[message])

assert.equal(true,value,message);

Thesimplestassertion.

Example:

varassert=require('assert');

functionadd(a,b){

returna+b;

}

varexpected=add(1,2);

assert(expected===3,'oneplustwoisthree');

Thiswillnothaveanyoutput.Ifyouwanttoseeoutput,youneedtomakethetestfail:

varassert=require('assert');

functionadd(a,b){

returna+b;

}

varexpected=add(1,2);

assert(expected===4,'oneplustwoisthree');

Output:

assert.js:92

thrownewassert.AssertionError({

^

AssertionError:oneplustwoisNOTfour

atObject.<anonymous>(/Users/n/code/node-js-by-example/core/assert/assert.js:8:1)

atModule._compile(module.js:456:26)

assert.ok(value,[message])isessentiallythesameasassert(value,message);

varassert=require('assert');

functionadd(a,b){

returna+b;

}

varexpected=add(1,2);

assert.ok(expected===3,'oneplustwoisthree');

Again,nooutputbecausethetestpasses.Toseesomefeedback,makethetestfail.

Usefulness:universal.assertcanbeusedtotestanycode.

Testsshallow,coerciveequalitywiththe(double)equalcomparisonoperator(==).

Ifyouwanttomakeyourtestcleareruseassert.equalotherwisethereisnobenefittotheadditionalverbosity.

Example:

assert.equal(actual,expected,[message])

Whywouldyouuseassert.equal()insteadofassert()?

varassert=require('assert');

functionadd(a,b){

returna+b;

}

varexpected=add(1,2);

//thesethreeassertionsareequivalent:

assert(expected==3,'oneplustwoisthree');

assert.ok(expected==3,'oneplustwoisthree');

assert.equal(expected,3,'oneplustwoisthree');

Testsshallow,coercivenon-equalitywiththenotequalcomparisonoperator(!=).

Example:

varassert=require('assert');

functionadd(a,b){

returna+b;

}

varexpected=add(1,2);

//thesethreeassertionsareequivalent:

assert(expected!=4,'oneplustwoisthree');

assert.ok(expected!=4,'oneplustwoisthree');

assert.notEqual(expected,4,'oneplustwoisthree(NOTFour!)');

Again,verbosity/clarityinyourtests.

Testsfordeepequality.

assert.deepEqualisthesecondoftheusefulmethods.Weuseitforcomparingtwoobjects(orarraysforequality).

Example:

varassert=require('assert');

varlist1=[1,2,3,4,5];

varlist2=[1,2,3,4,5];

assert.deepEqual(list1,list2,'deepEqualcheckstheelementsinthearraysareidentical');

varperson1={"name":"john","age":"21"};

varperson2={"name":"john","age":"21"};

//deepEqualcheckstheelementsintheobjectsareidentical

assert.deepEqual(person1,person2,'thesetwoobjectsarethesame');

Testsforanydeepinequality.Usefulwhenconfirmingtwoobjectsorarraysarenotequal.

Example:

assert.notEqual(actual,expected,[message])

Whywouldyouuseassert.notEqual(1,2)insteadofassert(1!=2)?

assert.deepEqual(actual,expected,[message])

assert.notDeepEqual(actual,expected,[message])

varassert=require('assert');

varlist1=[1,2,,3,4,5];

varlist2=[1,2,3,4,5];

assert.deepEqual(list1,list2,'deepEqualcheckstheelementsinthearraysareidentical');

varperson1={"name":"john","age":"21"};

varperson2={"name":"jane","age":"19"};

//deepEqualcheckstheelementsintheobjectsareidentical

assert.notDeepEqual(person1,person2,'thesetwoobjectsareNOTthesame');

Testsstrictequality,asdeterminedbythestrictequalityoperator(===)

Similartoassert.equalbut"strict"(typecoersion).

Example:

varassert=require('assert');

assert.strictEqual(1,'1','notthesame');//thiswillfail

Testsstrictnon-equality,asdeterminedbythestrictnotequaloperator(!==)

TheoppositeofthestrictEqual.

Example:

varassert=require('assert');

assert.notStrictEqual(1,true,'notthesame(strictly)');

Expectsblocktothrowanerror.errorcanbeconstructor,RegExporvalidationfunction.

Theassert.throwsletsyoucheckforspecificerrorsinyourfunctions.

Validateinstanceofusingconstructor:

Example:

assert.throws(

function(){

thrownewError("Wrongvalue");

},

Error

);

Expectsblocknottothrowanerror,seeassert.throwsfordetails.

Example:

assert.strictEqual(actual,expected,[message])

assert.notStrictEqual(actual,expected,[message])

assert.throws(block,[error],[message])

assert.doesNotThrow(block,[message])

assert.doesNotThrow(

function(){

console.log("Nothingtoseehere");

},

Error

);

Notparticularlyusefulmethodbecauseitstoovague.Itsgoodtoknowyourmethoddidnotthrowanerrorundernormalcircumstances.

Testsifvalueisnotafalsevalue,throwsifitisatruevalue.Usefulwhentestingthefirstargument,errorincallbacks.

Example:

//defineasimplefunctionwithcallback(err,value)

functionsayHello(name,callback){

varerror=false;

varstr="Hello"+name;

callback(error,str);

}

//usethefunction

sayHello('World',function(err,value){

assert.ifError(err);

assert.equal(value,"HelloWorld");

})

Aswithallcode,youcan'texpecttolearnwithouttrying.Opentheassert.jsfileinyoureditorandtryafewexamples.Rememberyouwon'tseeanyoutputunlessyourtestfails.Runitwiththecommand:

nodeassert.js

AssertAPI:http://nodejs.org/api/assert.htmlChrisJohansen'sintrotonodetesting:http://cjohansen.no/en/node_js/unit_testing_node_js_apps

Inthe"realworld"peoplerarelyusethenodeassertmodulebyits'self.Insteadatestrunnerisused.

ExamplesofNode.jstestrunnersinclude:

Mocha:https://github.com/visionmedia/mochaTape:https://github.com/substack/tapeLab:https://github.com/hapijs/lab

Eachofthesehastheirmeritsandwillbediscussedinalaterchapterontesting.

assert.ifError(value)

Tryit!

UsefulLinks

InPractice(The"RealWorld")

Buffersareaseriesofbytes.

Ifyouarecompletelynewtocomputerprogramming/science,here'saquickintrotoBits,BytesandOctets.

PureJavaScriptisUnicodefriendlybutnotnicetobinarydata.WhendealingwithTCPstreamsorthefilesystem,it'snecessarytohandleoctetstreams.Nodehasseveralwaysofmanipulating,creating,andconsumingoctetstreams.

BuffersareusedinternallybyNode.jsbutavailabletoeveryone.

Here'sasimpleexampleofcreatinganewBuffercontainingtheword"hello".Youwillnoticethatthebufferstoresthethehexadecimalvaluesforthecharacters.

Allocatesanewbufferofsizeoctets.

FeedingnewBuffer()anumericparametersimplyallocatesthatamountofmemorytothebufferforlateruse.

varbuf=newBuffer(10);//<Buffer10d633000100000000c8>

varstr=buf.toString();//�3�(incomprehensible-non-printablechars)

Practicaluse?None.(IfIfindoneIwillletyouknow.)

Allocatesanewbufferusinganarrayofoctets.

SimilartothenewBuffer(number)butallowsyoutopassinanarray;nodecreatesaplaceholderforeachelementinthearrayinyournewBuffer.

varbuf=newBuffer(['hello','world']);//<Buffer0000>

varstr=buf.toString();//empty

Practicaluse?None.

strString-stringtoencode.encodingString-encodingtouse,Optional.

Allocatesanewbuffercontainingthegivenstr.encodingdefaultsto'utf8'.

varbuf=newBuffer('hello');//<Buffer68656c6c6f>

varstr=buf.toString();//hello

Buffers

Whatdoesthatmean?

Buffers

newBuffer(size)

newBuffer(array)

newBuffer(str,[encoding])

encodingStringTheencodingstringtotest

Returnstrueiftheencodingisavalidencodingargument,orfalseotherwise.

console.log("Buffer.isEncoding('utf8')>>"+Buffer.isEncoding('utf8'));//true

Again,can'tseeapracticalapplicationforthis.

ReturnsaJSON-representationoftheBufferinstance,whichisidenticaltotheoutputforJSONArrays.JSON.stringifyimplicitlycallsthisfunctionwhenstringifyingaBufferinstance.

varbuf=newBuffer('test');

varjson=JSON.stringify(buf);

console.log(json);//'[116,101,115,116]'

varcopy=newBuffer(JSON.parse(json));

console.log(copy);//<Buffer74657374>

http://nodejs.org/api/buffer.html#buffer_bufferAsciitohextobinaryconversiontable:http://www.ascii-code.com

ClassMethod:Buffer.isEncoding(encoding)

buf.toJSON()

Abitisthebasicunitofinformationincomputinganddigitalcommunicationsusuallyexpressedas0(Zero)or1(One).Thewordbitisshortforbinarydigit.Binarymeanstherearetwooptionse.g:true/false,0/1oron/off

StartingatZero,thefirst16numbersinBinaryare:

+---+---+----+----+-----+-----+-----+-----+------+------+------+------+------+------+------+------+

|0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|

+---+---+----+----+-----+-----+-----+-----+------+------+------+------+------+------+------+------+

|0|1|10|11|100|101|110|111|1000|1001|1010|1011|1100|1101|1110|1111|

+---+---+----+----+-----+-----+-----+-----+------+------+------+------+------+------+------+------+

Didyouspotthepattern(s)?Ifnot,Isuggestyoureaduponcountingbinary:http://en.wikipedia.org/wiki/Binary_number

watch:https://www.youtube.com/watch?v=VBDoT8o4q00(howcomputerscount)

Abyteisaunitofdigitalinformationincomputingandtelecommunicationsthatmostcommonlyconsistsofeightbits.

010010000110010101101100011011000110111100100001

Hello!

Tryit:http://text2binary.herokuapp.com/

Hexadecimal

Inmathematicsandcomputing,hexadecimal(alsobase16,orhex)isapositionalnumeralsystemwitharadix,orbase,of16.Itusessixteendistinctsymbols,mostoftenthesymbols0–9torepresentvalueszerotonine,andA, B, C, D, E, F(oralternativelya–f)torepresentvaluestentofifteen.

Bits

CountinginBinary(bits)

Bytes

Hello!inBinary(8-BitASCII)

Hexadecimal