NNOODDEE.JJSS -- QQUUIICCKK GGUUIIDDEE - Tutorials Point

Transcription

NODE.JS - QUICK GUIDEhttp://www.tutorialspoint.com/nodejs/nodejs quick guide.htmCopyright tutorialspoint.comNODE.JS - INTRODUCTIONWhat is Node.js?Node.js is a web application framework built on Google Chrome's JavaScript EngineV8Engine. Itslatest version is v0.10.36. Defintion of Node.js as put by its official documentation is as follows:Node.js is a platform built on Chrome's JavaScript runtime for easily building fast,scalable network applications. Node.js uses an event-driven, non-blocking I/O modelthat makes it lightweight and efficient, perfect for data-intensive real-timeapplications that run across distributed devices.Node.js comes with runtime environment on which a Javascript based script can be interpreted andexecuted ItisanalogustoJVMtoJAVAbytecode. This runtime allows to execute a JavaScript code on anymachine outside a browser. Because of this runtime of Node.js, JavaScript is now can be executedon server as well.Node.js also provides a rich library of various javascript modules which eases the developement ofweb application using Node.js to great extents.Node.js Runtime Environment JavaScript LibraryFeatures of Node.jsAynchronous and Event DrivenAll APIs of Node.js library are aynchronous that is nonblocking. It essentially means a Node.js based server never waits for a API to return data.Server moves to next API after calling it and a notification mechanism of Events of Node.jshelps server to get response from the previous API call.Very Fast Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fastin code execution.Single Threaded but highly Scalable - Node.js uses a single threaded model with eventlooping. Event mechanism helps server to respond in a non-bloking ways and makes serverhighly scalable as opposed to traditional servers which create limited threads to handlerequests. Node.js uses a single threaded program and same program can services muchlarger number of requests than traditional server like Apache HTTP Server.No Buffering - Node.js applications never buffer any data. These applications simply outputthe data in chunks.License - Node.js is released under the MIT license.Who Uses Node.js?Following is the link on github wiki containing an exhaustive list of projects, application andcompanies which are using Node.js. This list include eBay, General Electric, GoDaddy, Microsoft,PayPal, Uber, Wikipins, Yahoo!, Yammer and the list continues.Projects, Applications, and Companies Using NodeConceptsThe following diagram depicts some important parts of Node.js which we will discuss in detail in thesubsequent chapters.

Where to Use Node.js?Following are the areas where Node.js is proving itself a perfect technology partner.I/O bound ApplicationsData Streaming ApplicationsData Intensive Realtime Applications DIRTJSON APIs based ApplicationsSingle Page ApplicationsWhere Not to Use Node.js?It is not advisable to use Node.js for CPU intensive applications.NODE.JS - ENVIRONMENT SETUPTry it Option OnlineYou really do not need to set up your own environment to start learning Node.js. Reason is verysimple, we already have set up Node.js environment online, so that you can compile and executeall the available examples online at the same time when you are doing your theory work. Thisgives you confidence in what you are reading and to check the result with different options. Feelfree to modify any example and execute it online.Try following example using Try it option available at the top right corner of the below samplecode box:console.log("Hello World!");For most of the examples given in this tutorial, you will find Try it option, so just make use of it andenjoy your learning.Local Environment SetupIf you are still willing to set up your environment for Node.js, you need the following two softwaresavailable on your computer, a Text Editor and b The Node.js binary installables.Text EditorThis will be used to type your program. Examples of few editors include Windows Notepad, OS Editcommand, Brief, Epsilon, EMACS, and vim or vi.Name and version of text editor can vary on different operating systems. For example, Notepadwill be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.The files you create with your editor are called source files and contain program source code. Thesource files for Node.js programs are typically named with the extension ".js".Before starting your programming, make sure you have one text editor in place and you haveenough experience to write a computer program, save it in a file, compile it and finally execute it.The Node.js Runtime

The source code written in source file is simply javascript. The Node.js interprter will be used tointerpret and execute your javascript code.Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windowsoperating systems with the 32-bit 386 and 64-bit amd64 x86 processor architectures.Following section guides you on how to install Node.js binary distribution on various OS.Download Node.js archiveDownload latest version of Node.js installable archive file from Node.js Downloads. At the time ofwriting this tutorial, I downloaded node-v0.12.0-x64.msi and copied it into C:\ nodejs folder.OSArchive nOSnode-v0.12.0-sunos-x86.tar.gzInstallation on UNIX/Linux/Mac OS X, and SunOSExtract the download archive into /usr/local, creating a NodeJs tree in /usr/local/nodejs. Forexample:tar -C /usr/local -xzf node-v0.12.0-linux-x86.tar.gzAdd /usr/local/nodejs to the PATH environment variable.OSOutputLinuxexport PATH PATH:/usr/local/nodejsMacexport PATH PATH:/usr/local/nodejsFreeBSDexport PATH PATH:/usr/local/nodejsInstallation on WindowsUse the MSI file and follow the prompts to install the Node.js. By default, the installer uses theNode.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejsdirectory in window's PATH environment variable. Restart any open command prompts for thechange to take effect.Verify installation: Executing a FileCreate a js file named test.js in C:\ Nodejs WorkSpace.File: test.jsconsole.log("Hello World")Now run the test.js to see the result:C:\Nodejs WorkSpace node test.jsVerify the OutputHello, World!NODE.JS - FIRST APPLICATION

Before creating actual Hello World ! application using Node.js, let us see the parts of a Node.jsapplication. A Node.js application consists of following three important parts:import required module: use require directive to load a javascript modulecreate server: A server which will listen to client's request similar to Apache HTTP Server.read request and return response: server created in earlier step will read HTTP requestmade by client which can be a browser or console and return the response.Creating Node.js ApplicationStep 1: import required moduleuse require directive to load http module.var http require("http")Step 2: create an HTTP server using http.createServer method. Pass it a function with parametersrequest and response. Write the sample implementation to always return "Hello World". Pass aport 8081 to listen method.http.createServer(function (request, response) {// HTTP Status: 200 : OK// Content Type: text/plainresponse.writeHead(200, {'Content-Type': 'text/plain'});// send the response body as "Hello World"response.end('Hello World\n');}).listen(8081);// console will print the messageconsole.log('Server running at http://127.0.0.1:8081/');Step 3: Create a js file named test.js in C:\ Nodejs WorkSpace.File: test.jsvar http require("http")http.createServer(function (request, response) {response.writeHead(200, {'Content-Type': 'text/plain'});response.end('Hello World\n');}).listen(8081);console.log('Server running at http://127.0.0.1:8081/');Now run the test.js to see the result:C:\Nodejs WorkSpace node test.jsVerify the Output. Server has startedServer running at http://127.0.0.1:8081/Make a request to Node.js serverOpen http://127.0.0.1:8081/ in any browser and see the below result.

NODE.JS - REPLREPL stands for Read Eval Print Loop and it represents a computer environment like a windowconsole or unix/linux shell where a command is entered and system responds with an output.Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.Read - Reads user's input, parse the input into JavaScript data-structure and stores inmemory.Eval - Takes and evaluates the data structurePrint - Prints the resultLoop - Loops the above command until user press ctrl-c twice.REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScriptcodes.FeaturesREPL can be started by simply running node on shell/console without any argument.C:\Nodejs WorkSpace nodeYou will see the REPL Command prompt:C:\Nodejs WorkSpace node Simple ExpressionLet's try simple mathematics at REPL command prompt:C:\Nodejs WorkSpace node 1 34 1 ( 2 * 3 ) - 43 Use variablesUse variables to store values and print later. if var keyword is not used then value is stored in thevariable and printed. Wheras if var keyword is used then value is stored but not printed. You canuse both variables later. Print anything usind console.logC:\Nodejs WorkSpace node x 1010 var y 10undefined x y20 console.log("Hello World")Hello WorkdundefinedMultiline ExpressionNode REPL supports multiline expression similar to JavaScript. See the following do-while loop in

action:C:\Nodejs WorkSpace node var x 0undefined do {. x ;. console.log("x: " x);. } while ( x 5 );x: 1x: 2x: 3x: 4x: 5undefined . comes automatically when you press enters after opening bracket. Node automatically checksthe continuity of expressions.Underscore variableUse to get the last result.C:\Nodejs WorkSpace node var x 10undefined var y 20undefined x y30 var sum undefined console.log(sum)30undefined REPL Commandsctrl c - terminate the current command.ctrl c twice - terminate the Node REPL.ctrl d - terminate the Node REPL.Up/Down Keys - see command history and modify previous commands.tab Keys - list of current commands.help - list of all commands.break - exit from multiline expression.clear - exit from multiline expression.save - save current Node REPL session to a file.load - load file content in current Node REPL session.C:\Nodejs WorkSpace node var x 10undefined var y 20undefined x y30 var sum undefined console.log(sum)30undefined

.save test.jsSession saved to:test.js .load test.js var x 10undefined var y 20undefined x y30 var sum undefined console.log(sum)30undefined NODE.JS - NPMnpm stands for Node Package Manager. npm provides following two main functionalities:Online repositories for node.js packages/modules which are searchable on search.nodejs.orgCommand line utility to install packages, do version management and dependencymanagement of Node.js packages.npm comes bundled with Node.js installables after v0.6.3 version. To verify the same, openconsole and type following command and see the result:C:\Nodejs WorkSpace npm --version2.5.1Global vs Local installationBy default, npm installs any dependency in the local mode. Here local mode refers to the packageinstallation in node modules directory lying in the folder where Node application is present.Locally deployed packages are accessible via require.Globally installed packages/dependencies are stored in user-directory /npm directory. Suchdependencies can be used in CLI CommandLineInterface function of any node.js but can not beimported using require in Node application directly.Let's install express, a popular web framework using local installation.C:\Nodejs WorkSpace npm install expressexpress@4.11.2 node modules\express -- merge-descriptors@0.0.2 -- utils-merge@1.0.0 -- methods@1.1.1 -- escape-html@1.0.1 -- fresh@0.2.4 -- cookie@0.1.2 -- range-parser@1.0.2 -- media-typer@0.3.0 -- cookie-signature@1.0.5 -- vary@1.0.0 -- finalhandler@0.3.3 -- parseurl@1.3.0 -- serve-static@1.8.1 -- content-disposition@0.5.0 -- path-to-regexp@0.1.3 -- depd@1.0.0 -- qs@2.3.3 -- debug@2.1.1 (ms@0.6.2) -- send@0.11.1 (destroy@1.0.3, ms@0.7.0, mime@1.2.11) -- on-finished@2.2.0 (ee-first@1.1.0) -- type-is@1.5.7 (mime-types@2.0.9) -- accepts@1.2.3 (negotiator@0.5.0, mime-types@2.0.9) -- etag@1.5.1 (crc@3.2.1) -- proxy-addr@1.0.6 (forwarded@0.1.0, ipaddr.js@0.1.8)Once npm completes the download, you can verify by looking at the content ofC:\Nodejs WorkSpace\node modules. Or type the following command:

C:\Nodejs WorkSpace npm lsC:\Nodejs WorkSpace -- express@4.11.2 -- accepts@1.2.3 -- mime-types@2.0.9 -- mime-db@1.7.0 -- negotiator@0.5.0 -- content-disposition@0.5.0 -- cookie@0.1.2 -- cookie-signature@1.0.5 -- debug@2.1.1 -- ms@0.6.2 -- depd@1.0.0 -- escape-html@1.0.1 -- etag@1.5.1 -- crc@3.2.1 -- finalhandler@0.3.3 -- fresh@0.2.4 -- media-typer@0.3.0 -- merge-descriptors@0.0.2 -- methods@1.1.1 -- on-finished@2.2.0 -- ee-first@1.1.0 -- parseurl@1.3.0 -- path-to-regexp@0.1.3 -- proxy-addr@1.0.6 -- forwarded@0.1.0 -- ipaddr.js@0.1.8 -- qs@2.3.3 -- range-parser@1.0.2 -- send@0.11.1 -- destroy@1.0.3 -- mime@1.2.11 -- ms@0.7.0 -- serve-static@1.8.1 -- type-is@1.5.7 -- mime-types@2.0.9 -- mime-db@1.7.0 -- utils-merge@1.0.0 -- vary@1.0.0Now Let's try installing express, a popular web framework using global installation.C:\Nodejs WorkSpace npm install express - gOnce npm completes the download, you can verify by looking at the content of userdirectory /npm/node modules. Or type the following command:C:\Nodejs WorkSpace npm ls -gInstalling a moduleInstallation of any module is as simple as typing the following command.C:\Nodejs WorkSpace npm install expressNow you can use it in your js file as following:var express require('express');Using package.jsonpackage.json is present in the root directoryt of any Node application/module and is used to definethe properties of a package. Let's open package.json of express package present inC:\Nodejs Workspace\node modules\express\{"name": "express","description": "Fast, unopinionated, minimalist web framework","version": "4.11.2",

"author": {"name": "TJ Holowaychuk","email": "tj@vision-media.ca"},"contributors": [{"name": "Aaron Heckmann","email": "aaron.heckmann github@gmail.com"},{"name": "Ciaran Jessup","email": "ciaranj@gmail.com"},{"name": "Douglas Christopher Wilson","email": "doug@somethingdoug.com"},{"name": "Guillermo Rauch","email": "rauchg@gmail.com"},{"name": "Jonathan Ong","email": "me@jongleberry.com"},{"name": "Roman Shtylman","email": "shtylman expressjs@gmail.com"},{"name": "Young Jae Sim","email": "hanul@hanul.me"}],"license": "MIT","repository": {"type": "git","url": ": "http://expressjs.com/","keywords": tful","router","app","api"],"dependencies": {"accepts": " 1.2.3","content-disposition": "0.5.0","cookie-signature": "1.0.5","debug": " 2.1.1","depd": " 1.0.0","escape-html": "1.0.1","etag": " 1.5.1","finalhandler": "0.3.3","fresh": "0.2.4","media-typer": "0.3.0","methods": " 1.1.1","on-finished": " 2.2.0","parseurl": " 1.3.0","path-to-regexp": "0.1.3","proxy-addr": " 1.0.6","qs": "2.3.3","range-parser": " 1.0.2","send": "0.11.1","serve-static": " 1.8.1","type-is": " 1.5.6","vary": " 1.0.0","cookie": "0.1.2","merge-descriptors": "0.0.2",

"utils-merge": "1.0.0"},"devDependencies": {"after": "0.8.1","ejs": "2.1.4","istanbul": "0.3.5","marked": "0.3.3","mocha": " 2.1.0","should": " 4.6.2","supertest": " 0.15.0","hjs": " 0.0.6","body-parser": " 1.11.0","connect-redis": " 2.2.0","cookie-parser": " 1.3.3","express-session": " 1.10.2","jade": " 1.9.1","method-override": " 2.3.1","morgan": " 1.5.1","multiparty": " 4.1.1","vhost": " 3.0.0"},"engines": {"node": " 0.10.0"},"files": b/"],"scripts": {"test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/test/acceptance/","test-cov": "istanbul cover node modules/mocha/bin/ mocha -- --requiretest/support/env --reporter dot --check-leaks test/ test/acceptance/","test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/test/acceptance/","test-travis": "istanbul cover node modules/mocha/bin/ mocha --report lcovonly -- -require test/support/env --reporter spec --check-leaks test/ test/acceptance/"},"gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada","bugs": {"url": "https://github.com/strongloop/express/issues"}," id": "express@4.11.2"," shasum": "8df3d5a9ac848585f00a0777601823faecd3b148"," from": "express@*"," npmVersion": "1.4.28"," npmUser": {"name": "dougwilson","email": "doug@somethingdoug.com"},"maintainers": [{"name": "tjholowaychuk","email": "tj@vision-media.ca"},{"name": "jongleberry","email": "jonathanrichardong@gmail.com"},{"name": "shtylman","email": "shtylman@gmail.com"},{"name": "dougwilson","email": "doug@somethingdoug.com"},{"name": "aredridel","email": "aredridel@nbtsc.org"},{

"name": "strongloop","email": "callback@strongloop.com"},{"name": "rfeng","email": "enjoyjava@gmail.com"}],"dist": {"shasum": l": 2.tgz"},"directories": {}," resolved": .2.tgz","readme": "ERROR: No README data found!"}Attributes of Package.jsonname - name of the packageversion - version of the packagedescription - description of the packagehomepage - homepage of the packageauthor - author of the packagecontributors - name of the contributors to the packagedependencies - list of dependencies. npm automatically installs all the dependenciesmentioned here in the node module folder of the package.repository - repository type and url of the packagemain - entry point of the packagekeywords - keywordsUninstalling a moduleUse following command to uninstall a module.C:\Nodejs WorkSpace npm uninstall expressOnce npm uninstall the package, you can verify by looking at the content of userdirectory /npm/node modules. Or type the following command:C:\Nodejs WorkSpace npm lsUpdating a moduleUpdate package.json and change the version of the dependency which to be updated and run thefollowing command.C:\Nodejs WorkSpace npm updateSearch a moduleSearch package name using npm.C:\Nodejs WorkSpace npm search expressCreate a moduleCreation of module requires package.json to be generated. Let's generate package.json usingnpm.C:\Nodejs WorkSpace npm init

This utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sane defaults.See 'npm help json' for definitive documentation on these fieldsand exactly what they do.Use 'npm install pkg --save' afterwards to install a package andsave it as a dependency in the package.json file.Press C at any time to quit.name: (Nodejs WorkSpace)Once package.json is generated. Use following command to register yourself with npm repositorysite using a valid email address.C:\Nodejs WorkSpace npm adduserNow its time to publish your module:C:\Nodejs WorkSpace npm publishNODE.JS - CALLBACKS CONCEPTWhat is Callback?Callback is an asynchronous equivalent for a function. A callback function is called at thecompletion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is sucha way that they supports callbacks. For example, a function to read a file may start reading file andreturn the control to execution environment immidiately so that next instruction can be executed.Once file I/O is complete, it will call the callback function while passing the callback function, thecontent of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.jshighly scalable, as it can process high number of request without waiting for any function to returnresult.Blocking Code ExampleCreate a txt file named test.txt in C:\ Nodejs WorkSpaceTutorialsPoint.ComCreate a js file named test.js in C:\ Nodejs WorkSpacevar fs require("fs");var data ing());console.log("Program Ended");Now run the test.js to see the result:C:\Nodejs WorkSpace node test.jsVerify the OutputTutorialsPoint.ComProgram EndedNon-Blocking Code ExampleCreate a txt file named test.txt in C:\ Nodejs WorkSpaceTutorialsPoint.ComUpdate test.js in C:\ Nodejs WorkSpacevar fs require("fs");fs.readFile('test.txt', function (err, data) {if (err) return console.error(err);

am Ended");Now run the test.js to see the result:C:\Nodejs WorkSpace node test.jsVerify the OutputProgram EndedTutorialsPoint.ComEvent Loop OverviewNode js is a single threaded application but it support concurrency via concept of event andcallbacks. As every API of Node js are asynchronous and being a single thread, it uses asyncfunction calls to maintain the concurrency. Node uses observer pattern. Node thread keeps anevent loop and whenever any task get completed, it fires the corresponding event which signalsthe event listener function to get executed.Event Driven ProgrammingNode.js uses Events heavily and it is also one of the reason why Node.js is pretty fast compared toother similar technologies. As soon as Node starts its server, it simply initiates its variables,delcares functions and then simply waits for event to occur.While Events seems similar to what callbacks are. The difference lies in the fact that callbackfunctions are called when an asynchronous function returns its result where event handling workson the observer pattern. The functions which listens to events acts as observer. Whenever anevent got fired, its listener function starts executing. Node.js has multiple in-built event. Theprimary actor is EventEmitter which can be imported using following syntax//import events modulevar events require('events');//create an eventEmitter objectvar eventEmitter new events.EventEmitter();ExampleCreate a js file named test.js in C:\ Nodejs WorkSpace.File: test.js//import events modulevar events require('events');//create an eventEmitter objectvar eventEmitter new events.EventEmitter();//create a function connected which is to be executed//when 'connection' event occursvar connected function connected() {console.log('connection succesful.');// fire the data received eventeventEmitter.emit('data received.');}// bind the connection event with the connected functioneventEmitter.on('connection', connected);// bind the data received event with the anonymous functioneventEmitter.on('data received', function(){console.log('data received succesfully.');});// fire the connection Program Ended.");

Now run the test.js to see the result:C:\Nodejs WorkSpace node test.jsVerify the Output. Server has startedconnection succesful.data received succesfully.Program Ended.How Node Applications Work?In Node Application, any async function accepts a callback as a last parameter and the callbackfunction accepts error as a first parameter. Let's revisit the previous example again.var fs require("fs");fs.readFile('test.txt', function (err, data) {if ata.toString());});console.log("Program Ended");Here fs.readFile is a async function whose purpose is to read a file. If an error occur during read offile, then err object will contain the corresponding error else data will contain the contents of thefile. readFile passes err and data to callback function after file read operation is complete.NODE.JS - EVENT EMITTEREventEmitter class lies in events module. It is accessibly via following syntax://import events modulevar events require('events');//create an eventEmitter objectvar eventEmitter new events.EventEmitter();When an EventEmitter instance faces any error, it emits an 'error' event. When new listener isadded, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.EventEmitter provides multiple properties like on and emit. on property is used to bind a functionwith the event and emit is used to fire an ent, listenerAdds a listener to the end of the listeners array for the specifiedevent. No checks are made to see if the listener has already beenadded. Multiple calls passing the same combination of event andlistener will result in the listener being added multiple times.Returns emitter, so calls can be chained.2onevent, listenerAdds a listener to the end of the listeners array for the specifiedevent. No checks are made to see if the listener has already beenadded. Multiple calls passing the same combination of event andlistener will result in the listener being added multiple times.Returns emitter, so calls can be chained.3onceevent, listenerAdds a one time listener for the event. This listener is invokedonly the next time the event is fired, after which it is removed.Returns emitter, so calls can be chained.4removeListenerRemove a listener from the listener array for the specified event.

event, listenerCaution: changes array indices in the listener array behind thelistener. removeListener will remove, at most, one instance of alistener from the listener array. If any single listener has beenadded multiple times to the listener array for the specified event,then removeListener must be called multiple times to removeeach instance. Returns emitter, so calls can be chained.5removeAllListeners[event]Removes all listeners, or those of the specified event. It's not agood idea to remove listeners that were added elsewhere in thecode, especially when it's on an emitter that you didn't createe. g. socketsorfilestreams. Returns emitter, so calls can be chained.6setMaxListenersnBy default EventEmitters will print a warning if more than 10listeners are added for a particular event. This is a useful defaultwhich helps finding memory leaks. Obviously not all Emittersshould be limited to 10. This function allows that to be increased.Set to zero for unlimited.7listenerseventReturns an array of listeners for the specified event.8emitevent, [arg1], [arg2], [. . . ]Execute each of the listeners in order with the suppliedarguments. Returns true if event had listeners, false otherwise.Class MethodsSr. No.methodDescription1listenerCountemitter, eventReturn the number of listeners for a given event.EventsSr.No.event name1newListenerParametersevent StringTheeventnameDescriptionThis event is emitted any time a listener is added.When this event is triggered, the listener may not yethave been added to the array of listeners for emoveListenerevent unctionThis event is emitted any time someone removes alistener. When this event is triggered, the listenermay not yet have been removed from the array oflisteners for the event.

ExampleCreate a js file named test.js in C:\ Nodejs WorkSpace.File: test.jsvar events require('events');var eventEmitter new events.EventEmitter();//listener #1var listner1 function listner1() {console.log('listner1 executed.');}//listener #2var listner2 function listner2() {console.log('listner2 executed.');}// bind the connection event with the listner1 functioneventEmitter.addListener('connection', listner1);// bind the connection event with the listner2 functioneventEmitter.on('connection', listner2);var eventListeners Emitter,'connection');console.log(eventListeners " Listner(s) listening to connection event");// fire the connection eventeventEmitter.emit('connection');// remove the binding of listner1 functioneventEmitter.removeListener('connection', listner1);console.log("Listner1 will not listen now.");// fire the connection s Emitter,'connection');console.log(eventListeners " Listner(s) listening to connection event");console.log("Program Ended.");Now run the test.js to see the result:C:\Nodejs WorkSpace node test.jsVerify the Output. Server has started2 Listner(s) listening to connection eventlistner1 executed.listner2 executed.Listner1 will not listen now.listner2 executed.1 Listner(s) listening to connection eventProgram Ended.NODE.JS - BUFFER MODULEbuffer module can be used to create Buffer and SlowBuffer classes. Buffer module can beimported using following syntax.var buffer require("buffer")Buffer classBuffer class is a global class and can be accessed in application without importing buffer module.A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside theV8 heap. A Buffer cannot be resized.

MethodsSr.No.method1new Buffersize2new Bufferbuffer3new Bufferstr[, encoding]Parameterssize NumberDescriptionAllocates a new bufferof size octets. Note,size must be no morethan kMaxLength.Otherwise, aRangeError will bethrown here.buffer BufferCopies the passedbuffer data onto anew Buffer instance.str String string toencode.Allocates a new buffercontaining the givenstr. encoding defaultsto 'utf8'.encodingString encoding touse,Optional.4buf.length5buf.writestring[, offset][, length][, encoding]Return: Numberstring String- data to bewritten tobufferThe size of the bufferin bytes. Note that thisis not necessarily thesize of the contents.length refers to theamount of memoryallocated for thebuffer object. It doesnot change when thecontents of the bufferare changed.Allocates a new buffercontaining the givenstr. encoding defaultsto 'utf8'.offsetNumber,Optional,Default: 0lengthNumber,Optional,Default:buffer.length- riteUIntLEvalue, offset, byteLength[, noAssert]value{Number}Bytes to beWrites value to thebuffer at the specifiedoffset and byteLe

Online repositories for node.js packages/modules which are searchable on search.nodejs.org Command line utility to install packages, do version management and dependency management of Node.js packages. npm comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and type following command and see the result: