Nnooddee.jjss -- Qquuiicckk Gguuiiddee

1y ago
21 Views
2 Downloads
595.46 KB
76 Pages
Last View : Today
Last Download : 3m ago
Upload by : Laura Ramon
Transcription

NODE.JS - QUICK GUIDE http://www.tutorialspoint.com/nodejs/nodejs quick guide.htm Copyright tutorialspoint.com NODE.JS - INTRODUCTION What is Node.js? Node.js is a web application framework built on Google Chrome's JavaScript EngineV8Engine. Its latest 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 model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js comes with runtime environment on which a Javascript based script can be interpreted and executed ItisanalogustoJVMtoJAVAbytecode. This runtime allows to execute a JavaScript code on any machine outside a browser. Because of this runtime of Node.js, JavaScript is now can be executed on server as well. Node.js also provides a rich library of various javascript modules which eases the developement of web application using Node.js to great extents. Node.js Runtime Environment JavaScript Library Features of Node.js Aynchronous 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.js helps 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 fast in code execution. Single Threaded but highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server. No Buffering - Node.js applications never buffer any data. These applications simply output the 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 and companies 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 Node Concepts The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters.

Where to Use Node.js? Following are the areas where Node.js is proving itself a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Realtime Applications DIRT JSON APIs based Applications Single Page Applications Where Not to Use Node.js? It is not advisable to use Node.js for CPU intensive applications. NODE.JS - ENVIRONMENT SETUP Try it Option Online You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. Try following example using Try it option available at the top right corner of the below sample code 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 and enjoy your learning. Local Environment Setup If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, a Text Editor and b The Node.js binary installables. Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will 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. The source 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 have enough 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 to interpret and execute your javascript code. Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating 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 archive Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, I downloaded node-v0.12.0-x64.msi and copied it into C:\ nodejs folder. OS Archive name Windows node-v0.12.0-x64.msi Linux node-v0.12.0-linux-x86.tar.gz Mac node-v0.12.0-darwin-x86.tar.gz SunOS node-v0.12.0-sunos-x86.tar.gz Installation on UNIX/Linux/Mac OS X, and SunOS Extract the download archive into /usr/local, creating a NodeJs tree in /usr/local/nodejs. For example: tar -C /usr/local -xzf node-v0.12.0-linux-x86.tar.gz Add /usr/local/nodejs to the PATH environment variable. OS Output Linux export PATH PATH:/usr/local/nodejs Mac export PATH PATH:/usr/local/nodejs FreeBSD export PATH PATH:/usr/local/nodejs Installation on Windows Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejs directory in window's PATH environment variable. Restart any open command prompts for the change to take effect. Verify installation: Executing a File Create a js file named test.js in C:\ Nodejs WorkSpace. File: test.js console.log("Hello World") Now run the test.js to see the result: C:\Nodejs WorkSpace node test.js Verify the Output Hello, World! NODE.JS - FIRST APPLICATION

Before creating actual Hello World ! application using Node.js, let us see the parts of a Node.js application. A Node.js application consists of following three important parts: import required module: use require directive to load a javascript module create 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 request made by client which can be a browser or console and return the response. Creating Node.js Application Step 1: import required module use 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 parameters request and response. Write the sample implementation to always return "Hello World". Pass a port 8081 to listen method. http.createServer(function (request, response) { // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // send the response body as "Hello World" response.end('Hello World\n'); }).listen(8081); // console will print the message console.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.js var 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.js Verify the Output. Server has started Server running at http://127.0.0.1:8081/ Make a request to Node.js server Open http://127.0.0.1:8081/ in any browser and see the below result.

NODE.JS - REPL REPL stands for Read Eval Print Loop and it represents a computer environment like a window console 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 in memory. Eval - Takes and evaluates the data structure Print - Prints the result Loop - 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 JavaScript codes. Features REPL can be started by simply running node on shell/console without any argument. C:\Nodejs WorkSpace node You will see the REPL Command prompt: C:\Nodejs WorkSpace node Simple Expression Let's try simple mathematics at REPL command prompt: C:\Nodejs WorkSpace node 1 3 4 1 ( 2 * 3 ) - 4 3 Use variables Use variables to store values and print later. if var keyword is not used then value is stored in the variable and printed. Wheras if var keyword is used then value is stored but not printed. You can use both variables later. Print anything usind console.log C:\Nodejs WorkSpace node x 10 10 var y 10 undefined x y 20 console.log("Hello World") Hello Workd undefined Multiline Expression Node REPL supports multiline expression similar to JavaScript. See the following do-while loop in

action: C:\Nodejs WorkSpace node var x 0 undefined do { . x ; . console.log("x: " x); . } while ( x 5 ); x: 1 x: 2 x: 3 x: 4 x: 5 undefined . comes automatically when you press enters after opening bracket. Node automatically checks the continuity of expressions. Underscore variable Use to get the last result. C:\Nodejs WorkSpace node var x 10 undefined var y 20 undefined x y 30 var sum undefined console.log(sum) 30 undefined REPL Commands ctrl 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 10 undefined var y 20 undefined x y 30 var sum undefined console.log(sum) 30 undefined

.save test.js Session saved to:test.js .load test.js var x 10 undefined var y 20 undefined x y 30 var sum undefined console.log(sum) 30 undefined NODE.JS - NPM npm stands for Node Package Manager. npm provides following two main functionalities: 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: C:\Nodejs WorkSpace npm --version 2.5.1 Global vs Local installation By default, npm installs any dependency in the local mode. Here local mode refers to the package installation 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. Such dependencies can be used in CLI CommandLineInterface function of any node.js but can not be imported using require in Node application directly. Let's install express, a popular web framework using local installation. C:\Nodejs WorkSpace npm install express express@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 of C:\Nodejs WorkSpace\node modules. Or type the following command:

C:\Nodejs WorkSpace npm ls C:\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.0 Now Let's try installing express, a popular web framework using global installation. C:\Nodejs WorkSpace npm install express - g Once 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 -g Installing a module Installation of any module is as simple as typing the following command. C:\Nodejs WorkSpace npm install express Now you can use it in your js file as following: var express require('express'); Using package.json package.json is present in the root directoryt of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in C:\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": "https://github.com/strongloop/express" }, "homepage": "http://expressjs.com/", "keywords": [ "express", "framework", "sinatra", "web", "rest", "restful", "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": [ "LICENSE", "History.md", "Readme.md", "index.js", "lib/" ], "scripts": { "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", "test-cov": "istanbul cover node modules/mocha/bin/ mocha -- --require test/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": "8df3d5a9ac848585f00a0777601823faecd3b148", "tarball": 2.tgz" }, "directories": {}, " resolved": .2.tgz", "readme": "ERROR: No README data found!" } Attributes of Package.json name - name of the package version - version of the package description - description of the package homepage - homepage of the package author - author of the package contributors - name of the contributors to the package dependencies - list of dependencies. npm automatically installs all the dependencies mentioned here in the node module folder of the package. repository - repository type and url of the package main - entry point of the package keywords - keywords Uninstalling a module Use following command to uninstall a module. C:\Nodejs WorkSpace npm uninstall express Once 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 ls Updating a module Update package.json and change the version of the dependency which to be updated and run the following command. C:\Nodejs WorkSpace npm update Search a module Search package name using npm. C:\Nodejs WorkSpace npm search express Create a module Creation of module requires package.json to be generated. Let's generate package.json using npm. 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 fields and exactly what they do. Use 'npm install pkg --save' afterwards to install a package and save 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 repository site using a valid email address. C:\Nodejs WorkSpace npm adduser Now its time to publish your module: C:\Nodejs WorkSpace npm publish NODE.JS - CALLBACKS CONCEPT What is Callback? Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks. For example, a function to read a file may start reading file and return 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, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result. Blocking Code Example Create a txt file named test.txt in C:\ Nodejs WorkSpace TutorialsPoint.Com Create a js file named test.js in C:\ Nodejs WorkSpace var fs require("fs"); var data fs.readFileSync('test.txt'); console.log(data.toString()); console.log("Program Ended"); Now run the test.js to see the result: C:\Nodejs WorkSpace node test.js Verify the Output TutorialsPoint.Com Program Ended Non-Blocking Code Example Create a txt file named test.txt in C:\ Nodejs WorkSpace TutorialsPoint.Com Update test.js in C:\ Nodejs WorkSpace var fs require("fs"); fs.readFile('test.txt', function (err, data) { if (err) return console.error(err);

console.log(data.toString()); }); console.log("Program Ended"); Now run the test.js to see the result: C:\Nodejs WorkSpace node test.js Verify the Output Program Ended TutorialsPoint.Com Event Loop Overview Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed. Event Driven Programming Node.js uses Events heavily and it is also one of the reason why Node.js is pretty fast compared to other 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 callback functions are called when an asynchronous function returns its result where event handling works on the observer pattern. The functions which listens to events acts as observer. Whenever an event got fired, its listener function starts executing. Node.js has multiple in-built event. The primary actor is EventEmitter which can be imported using following syntax //import events module var events require('events'); //create an eventEmitter object var eventEmitter new events.EventEmitter(); Example Create a js file named test.js in C:\ Nodejs WorkSpace. File: test.js //import events module var events require('events'); //create an eventEmitter object var eventEmitter new events.EventEmitter(); //create a function connected which is to be executed //when 'connection' event occurs var connected function connected() { console.log('connection succesful.'); // fire the data received event eventEmitter.emit('data received.'); } // bind the connection event with the connected function eventEmitter.on('connection', connected); // bind the data received event with the anonymous function eventEmitter.on('data received', function(){ console.log('data received succesfully.'); }); // fire the connection event eventEmitter.emit('connection'); console.log("Program Ended.");

Now run the test.js to see the result: C:\Nodejs WorkSpace node test.js Verify the Output. Server has started connection 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 callback function 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 (err){ console.log(err.stack); return; } console.log(data.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 of file, then err object will contain the corresponding error else data will contain the contents of the file. readFile passes err and data to callback function after file read operation is complete. NODE.JS - EVENT EMITTER EventEmitter class lies in events module. It is accessibly via following syntax: //import events module var events require('events'); //create an eventEmitter object var eventEmitter new events.EventEmitter(); When an EventEmitter instance faces any error, it emits an 'error' event. When new listener is added, '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 function with the event and emit is used to fire an event. Methods Sr. No. method Description 1 addListener event, listener Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained. 2 onevent, listener Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained. 3 onceevent, listener Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained. 4 removeListener Remove a listener from the listener array for the specified event.

event, listener Caution: changes array indices in the listener array behind the listener. removeListener will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified event, then removeListener must be called multiple times to remove each instance. Returns emitter, so calls can be chained. 5 removeAllListeners [event] Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's on an emitter that you didn't create e. g. socketsorfilestreams. Returns emitter, so calls can be chained. 6 setMaxListenersn By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited. 7 listenersevent Returns an array of listeners for the specified event. 8 emit event, [arg1], [arg2], [. . . ] Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise. Class Methods Sr. No. method Description 1 listenerCountemitter, event Return the number of listeners for a given event. Events Sr. No. event name 1 newListener Parameters event String The event name Description This event is emitted any time a listener is added. When this event is triggered, the listener may not yet have been added to the array of listeners for the event. listener Function The event handler function 2 removeListener event String The event name listener Function The event handler function This event is emitted any time someone removes a listener. When this event is triggered, the listener may not yet have been removed from the array of listeners for the event.

Example Create a js file named test.js in C:\ Nodejs WorkSpace. File: test.js var events require('events'); var eventEmitter new events.EventEmitter(); //listener #1 var listner1 function listner1() { console.log('listner1 executed.'); } //listener #2 var listner2 function listner2() { console.log('listner2 executed.'); } // bind the connection event with the listner1 function eventEmitter.addListener('connection', listner1); // bind the connection event with the listner2 function eventEmitter.on('connection', listner2); var eventListeners Emitter,'connection'); console.log(eventListeners " Listner(s) listening to connection event"); // fire the connection event eventEmitter.emit('connection'); // remove the binding of listner1 function eventEmitter.removeListener('connection', listner1); console.log("Listner1 will not listen now."); // fire the connection event eventEmitter.emit('connection'); eventListeners 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.js Verify the Output. Server has started 2 Listner(s) listening to connection event listner1 executed. listner2 executed. Listner1 will not listen now. listner2 executed. 1 Listner(s) listening to connection event Program Ended. NODE.JS - BUFFER MODULE buffer module can be used to create Buffer and SlowBuffer classes. Buffer module can be imported using following syntax. var buffer require("buffer") Buffer class Buffer 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 the V8 heap. A Buffer cannot be resized.

Methods Sr. No. method 1 new Buffersize 2 new Bufferbuffer 3 new Bufferstr[, encoding] Parameters size Number Description Allocates a new buffer of size octets. Note, size must be no more than kMaxLength. Otherwise, a RangeError will be thrown here. buffer Buffer Copies the pass

Node.js is a web application framework built on Google Chrome's JavaScript EngineV8Engine. Its latest 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 .

Related Documents:

Screw-Pile in sand under compression loading (ignoring shaft resistance) calculated using Equation 1.5 is shown in Figure 3. The influence of submergence on the calculated ultimate capacity is also shown. The friction angle used in these calculations is the effective stress axisymmetric (triaxial compression) friction angle which is most appropriate for Screw-Piles and Helical Anchors. 8 .

We can use VBA in all office versions right from MS-Office 97 to MS-Office 2013 and also with any of the latest versions available. Among VBA, Excel VBA is the most popular one and the reason for using VBA is that we can build very powerful tools in MS Excel using linear programming. Application of VBA

GWT compiles the code written in JAVA to JavaScript code. Application written in GWT is cross-browser compliant. GWT automatically generates javascript code suitable for each browser. GWT is open source, completely free, and used by thousands of developers around the wo

What is Twitter Bootstrap? Bootstrap is a sleek, intuitive, and powerful, mobile first front-end framework for faster and easier web development. It uses HTML, CSS and Javascript. History Bootstrap was developed by Mark Otto and Jacob Thornton at Twitter. It was released as an open source product in August 2011 on GitHub. Why Use Bootstrap?

What is Bootstrap Grid System? As put by the official documentation of Bootstrap for grid system: Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful mixins for generating

Physical Gate Length 90nm 32nm 18nm 9nm Technologyy NNooddee Maintaining historical CMOS performance trend requires new semiconductor material and structures by 2008-2010 Earlier if current bulk-Si data do not improve significantly MOSFET in Bulk Si 4 Saraswat - EE311/Future Devices araswat tanford University 0.001 0.01 0.1 2000 2010 2020 .

Step 1 - Create Java Project: The first step is to create a Dynamic Web Project using Eclipse IDE. Follow the option File - New- Project and finally select Dynamic Web Project wizard from the wizard list. Now name your project as UserManagement using the wizard window as follows:

2020 Manual for Railway Engineering (MRE) – Individual/Downloadable Chapters in PDF format. Visit www.arema.org Publication Title Member Price Non-Member Price S & H Fee Schedule Quantity Total Cost 2020 Manual for Railway Engineering (MRE) – Annual Publication released every April Complete Print Set 960 1,470 1