FSWD Tech Pub
FSWD Tech Pub
” eftersords to install a package end gave it 25 a dependency in the package, json file °C at any tine to quit : chage nase’ (node jsexergles) i TECHNICAL PUBLICATIONS® - an up-hrust for knowledgeFull Stack Web Development 2-9 NODE JS_ Bice | About to write to D:\Wlode3SExamples\package. json tversion”: "1.0.1", Tdescription": “this is my first package! II", | cnain": "callbackOero. js", | Tseripts™: ( | Mtest®: “runpackoge" » | ‘Tname": “mypackage”, | wuthor" “License’ “A.A.Puntanbekar”, ree 5s this OK? (yes) yes : Wode3SExamples> vi} * Once you execute the above commands, the package.json gets created. You can open and test it using a simple notepad. Node,js Built in Modules * Module is nothing but the set of functions that can be used in our application. Node.js has various built in modules that can be used in our application without any installation, * To include the module, we use require() function with the name of the module. Let us discuss some important built-in modules. (1) assert * This module is used during the testing of expressions. If an expression evaluates to 0 of false, an error is thrown and the program gets terminated, Step 1: Open Notepad and create a js file as follows. I have created an application using the name app,js. Here is the code. appjs var assert = require(‘assert'); assert(10 , EZ Creating a The console object is a global object which is used to print different levels of messages to ple Node.js Application stdout and stderr. The most commonly used methods console object are console.log console.info, console.wam and console.error. Let us discuss them with illustrative examples, 1) consolelog({data]}, ...]) : It is used for printing to stdout with newline. This function can take multiple arguments similar to a printf statement in C. console1.js [var emp_name = ‘Ankita, { ‘console.log('Name; %s'+\n'+.’Departments: i/iemp_name, emp_depts); TECHNICAL PUBLICATIONS® - an up-trust for knowledgeFull Stack Web Development 2-12 Noy Output Vee oer lame: Ankite ae eee ee coe Pavers ona 2) console.info(|data]]. ...) : This method is similar to console.log. console2.js ‘ar emp_name = ‘Ani emp depts { dept: Sales. dep? Accoun ‘console info(Name: %s'+\\n'+ ‘Departments: ‘xjemp_name, emp_depts); Output (ame! Ankita Departments: {"deptt'"Seles’."dept2"Accounts'} 3) console.error ({datal|, ..]) : This method prints to stderr with newline console3,js var code = 401 ‘console.error(Error!!code) : Output Beoxla07 4) console.warn({datalf, ..]) : This method is similar to console.error() method. Consider following example - In which using the fs module we open a text file. If the file does not open successfully then console.warn() method displays the warning message. consoles. var fs = require(‘e!); fs.open(‘input dat’,'r’function(errf){ ifer) console.wam(err); else console.log(’File opening successfall!’) v TECHNICAL PUBLICATIONS? - an up-thrust for knowtedgeFull Stack Web Development 2-42 NODE JS Output | BI Command Prompt x || | SDC eat ae ue etn Ottis cece aeste Cen coy syscoll: Enea i pcos soa Review Question plain any four methods of console object in node.js with suitable examples. Ea Using Events © Event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs/threads Event loop Eventemitter -—=} Event queue Event handlers. Fig. 2.6.1 Event driven architecture in node.js What is an Event ? ‘© Bvery time when a user interacts with the webpage, an event occurs when the user clicks the mouse button or presses some key on the keyboard. © When events are triggered, some functions associated with these events get executed + Event driven programming makes use of the following concepts = i) When some events occur, an event handler function is called. This is basically a call back function. ii) The main program listens to every event getting triggered and calls the associated event handler for that event. TECHNICAL PUBLICATIONS® - an yp-inrust for KnowiodgaFull Stack Web Development 214 __Nony Concept of Event Emitter : * The Even emitter is a module that facilitates comnninication between objects © The emitter objects performs following tasks - 1) Itemits named events. 2) Registed and unregisted listener functions, Basically EventEmitter is a class which can be used to raise and handle custom event, + Following are some commonly used methods of EventEmitter class, Method | Purpose This function adds the listener function to the end of the listeners array for the specified event. ‘on(event, listener) listener is invoked ‘once(event, listener) Adds a one-time listener for the event. TI only the next time the event is fired, after which it is removed. emit(event, fargi}. farg2}.[..]) | Raise the specified events with the supplied arguments, Steps for using event handling in Nodes Step 1 : import the ‘events’ module and create an instance of it using following code - vat events = require(events}, SE Step 2 :Then create an instance of EventEmitter() class. This instance is created because we have to call on() and emit() functions using this instance. Step 3: Then define a callback function which should be called on occurrence of an event. This function is also called as event listener function. Step 4 : Then register the event using the on() function. To this function name of the event and callback function is passed as arguments. Step 5 : Finally raise the event using the emit() function. Example Code eventDemot js ‘//get the reference of EventEmitter class of events module var events = require(events); Wereate an object of EventEmitter class by using above reference var em = new events EventEmitter(); |var myfunction = function() { | console Jog("When event occure, My Function is called") ee: TECHNICAL PUBLICATIONS® - an up-thrust for knowledgoFull Stack Web Development 2215 NODE JS //Bind FirstEvent with myfunction om.on(FirstEvent’, myfunction) J/ Raising FirstEvent ememit(FirstE vent); Output D:\NodeJSExamplos>node eventDemol je When event occurs, My Function is called. Program Explanation : In above program, 1) We have to import the ‘events’ module. 2) Then we create an object of the EventEmitter class. 3) For specifying the event handler function, we need to use the on() function. 4) The on() function requires two parameters - Name of the event to be handled and the callback function which is called when an event is raised. 5) The emit() function raises the specified event. Example code for passing data along with event We can pass some data inside the event, following example illustrate the same - eventDemot, // got the reference of EventEmitter class of events module var events = require(‘events'}; /eroate an object of EventEmitter class by using above reference ‘var em = new events. EventEmitter(); var myfunction = function(datat,data2) { console.log("When event occurs, My Function is called"); console.log("Data passed is: “+datal+" "+data2); } //Bind FirstEvent with myfunction em.on(FirstEvent’, myfunction); |// Raising FirstEvent lem.emit(FirstE vent’ datat /data2! Output [D\\NedeJStxamples>node eventDemot js When event occurs, My Function ig called ‘Data passed is: datal data2 TECHNICAL PUBLICATIONS® - on upannst for knowodyeFull Stack Web Development 2 18 ____Nony EXGHI Concept of Event Loop + Node Js isa single threaded system. So it executes the next task only after compretin, previous task * The event loop allows Nodes to perform non-blocking VO operations evenit ) JavaScript is single threaded. * Event loop is an endless loop which waits for tasks, executes these tasks and sleeps 1 it receives next task ‘© The event loop allows us to use callback functions, ‘+ The event loop executes task from event queue only when the call stack is empty, Emp call stack means there is no ongoing task. | © Event loop makes execution fast. Event Loop Execution Model JavaScript Engine Thvead 00 myappis | Calistack Sous eran Doo FTaski_--—Taskr Execute calback| Fig. 2.6.2 Event loop execution * The Event Loop is 2 main loop running continuously for executing the callback functions. When an asyne function executes, the callback function is pushed into the | queue. The JavaScript engine doesn't start processing the event loop until the code afier an async function has executed. Example Code console.log("Task1"); console log(Task2"); setTimeout(function() {console log("Task2") },1000); ‘console log("Take4"); TECHNICAL PUBLICATIONS® - on up-tiust for knowiedgeFull Stack Wob Development 2-17 NODE JS Output (Command Prompt 0: \NodeJSExamples>node EventLoopDemo. js aski ask2 aks4 ask3 :\NodeJSExamples>,, Phases of Event Loop Various phases of event loop are - Pending Callbacks (= | ae Fig. 2.6.3 TECHNICAL PUBLICATIONS® - an up.tnrst for knowledgeFull Stack Web Development 228 Wy 1) Timers This is the first phase in the event loop. It finds expired timers iny ¢, iteration (also known as Tick) and executes the timers callbacks co.) by setTimout and setInterval. 2) Pending callbacks : It handles VO callbacks deferred to the next iteration, such handling TCP socket connection error. 3) Idle. prepare : It is used intemally. 4) Poll : The Poll phase calculates the blocking time in every iteration to handle |, callbacks, 5) Check : This phase handles the callbacks scheduled by setImmediate(), and the callbacks will be executed once the Poll phase becomes idle. 6) Close callback : This phase handles callbacks if'a socket or handle is closed suddenly and the “close” event will be emitted. Listeners * An event listener is a technique or a function that waits for an event to occur. The listener is programmed to react to an input or signal by calling the event's handler. * The event module allows us to create and handle custom events in Nodes. * The EventEmitter class is used to raise and handle the events. ¢ Following are some commonly used properties and methods that implements the even listeners. a, Method Purpose | 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 listerier has already been added. It can also be called as an alias of emitter.addListenerQ) con(event, listener) Removes a listener from the listener array for the specified event, Caution : Changes array indices in the listener array | behind the listener. removeL istener(event, listener) Removes all listeners, or those of the specified event. removeAllListeners([event]}) listeners(event) Itretums an array of listeners for specified event listenerCount(event) It returns the number of listeners listening to the specified events, It will add the one-time listener to the beginning of the array. prependOnceListenerfevem, listener) TECHNICAL PUBLICA TIONS® - an up-thrust for knowledgeFull Stack Wot Development NODE JS setMaxl isteners(int) This method sets the number of listeners to the particular event. By default a maximum of 10 listeners can be registered for any single event getMaxt isteners() | It will return the max listeners value set by setMaxListeners() or default value 10. Example Code var events = requiro(events}); var oventEmitter = new events. EventEmitter(); // Bvent listener #1 var listoner1 = function listener1() ( console log(‘Event listener#1 executed.’); + // Event listener #2 var listener2 = function listener2() { console.log('Event listener#2 executed.’); } // Event listener #3 var listener3 = function listener3() { console.log(‘Event listener#3 executed. } // Bind the ‘myevent’ event with the listenert function eventEmitter.addListener(‘myevent,, listener1); 1/ Bind the 'myevent' event with the listener2 function eventEmitter.on(myevent, listener2); eventEmitter.on(‘myevent, listener3); /MRaise the events aventEmitter.omit(‘myevent ‘7Display total number of events sonsole.log(*Number of Eventlisteners are: "+oventEmitter listenerCount(myevent)); ‘Display the current status of event queue sonsole.log("Following are the events in the quoue...\n"}; sonsole.log(eventEmitter.listeners('myevent)); / Remove the binding of listener! function ventEmitter.removeListener( myevent, listener); TECHNICAL PUBLICATIONS® - an up-inrust for knowiedgeFull Stack Web Development 2-20 Nop ‘console log(‘Event Listenet#1 is removed); [Display the current status of event queue : console log("Following are the events in the queue...\n"); console log(eventEmitter listeners(myevent)}; ; ‘console log("Number of Eventlisteners are: 'eventEmitter.listenerCount(myevent')); ‘//Removing all the events ‘console Jog("Removing all the events."); ‘eventEmitter removeAllListeners(myevent)) //Bisplay the current status of event queue ‘console lou(Following are the events in the queue...\n"); console Jog(eventEmitter listeners(myevent)); ‘console.log("Number of Eventlisteners are: "+ eventEmitter_listenerCount(‘myevent')); Output | ‘Event listener#1 executed. Event listener#2 executed, ‘Event listener#3 executed, ‘Number of Eventlisteners are: 3 i Following are the events in the queue... { {Function: listener, (Function: listener2], [Function: listener} | ‘Event Listener#1 is removed Following ere the events in the queue. Function: listener2], [Function: listener3} | ‘Number of Eventlisteners are: 2 ‘Removing all the events, Following are the events in the queue... a ‘Number of Eventlisteners are: 0 Program Explanatior In above program, 1. Three functions are created as event listeners. Then using eventEmitter.addListener() and eventEmitter.on() methods are used to bind the events with the corresponding functions, 2. Then using eventEmitter.event() method, the events are raised, 3. We have used the eventEmitter.listenerCount() method to get the total number of events that are active, 4. The eventEmitter.listeners() method is used to display the array of registered events TECHNICAL PUBLICA TIONS® - an. ‘up-thrust for knowledgeFull Stack Web Development 2-21 NODE JS 5. We have also used removeListener() method to remove one listener and removeAlllisteners() method to remove all the listeners. Bl Timers * Timers module in Node js provides a way for scheduling the functions to be executed ‘on some given time. * For using the timers module in Node,js it is not required to import it via required) funetic as all the methods are globally available to JavaScript API. Hence we do not have to use “require” in the source code while using timer functions © There are three set timer functions us ctTimeout() 2. setimmediate() 3. setInterval() Let us understand them with suitable examples - 1) setTimeout() : ‘This function is used to set one time callback after delaying by some milliseconds. Syntax ‘setTimeout(function,delay_in milliseconds) Timert js console log "Taste!" setTimeout(function() {console.log("Taks2:Executing After 4 seconds") },4000); console.log(Task3"); Output fH Command Prompt - oa x | 1D: \NodeJSExamples>node Timer1. js | ask1 ‘ask3 ‘aks2:Executing After 4 seconds :\Node)SExamples> \| TECHNICAL PUBLICATIONS® - an up-inust for snowiedgee-.-.-S.SC!”””tt~—” 7y 22 er. Full Stack Web Development 2 Example code for the function having some parameters ‘We will now discuss to use setTimeout function for aocepting 2 function with paranc) “The fanction that will be passed to se{Timeout alone swith parameters has following synia, |Geitimeout{hitiction nate, Gelay_in_millisecontis.parem Timer2,s, - 4 . [GGasbie log(*Greeting message will be displayed toon.) jvar myfun = (user) { ‘consoleJog(‘Good Morning "+user): a s \setTimeout{myfun,1000,"Ankita’); teri parameter.) Output BB Command Prompt i [D: \WodeISExemples>node timer2.js &§ Ireeting message will be displayed soon... : Good Horning Ankita |D:\NodeIsexamples>, 2) setimmediate() : This function schedules the immediate execution of the callback function afier 1/O event. The syntax is (setimmediato(=>7 3 | dffanction body i » s Z sie We don't need to pass any time interval 1o this method. The first argument is the function to execute, We can also pass any extra arguments to this function . This method will execute 2 function right after the next code block which is present alter the setImmediate function. For example - [console log("Startedil!"); ‘potimmediate(()=> {- | consote log(Now Exocuting sectImmediate Block. Dy TECHNICAL PUBLICATIONS® «an up.thust for nowtodgeFull Stack Web Development 2.29 NODE JS Note that those console.Jog statements will execute first and then immediately after that the sotimmediate function will execute. console log(Task!" console log("Taks2'); Wide SExaeplesonede timer. js tarted!!) Cuecuting setterediate Block WiodesSexamples> 3) setInteryal() : This function helps to execute a task in a loop after some time interval. This function has the same syntax as that of setTimeout. Syntax timerld = setinterval(fune| code, (delay), [arg1]. [arg2l. For example var myfun = () => { console.log("Hello” } setInterval(myfun, 1000); Output [BY commana romot a Wide2stxaeplessnode tier}. js ode SExamples>, TECHNICAL PUBLICATIONS® - an up-tnrust for knowledge:ee | Full Stack Web Development. 2-24 om The above code present in the function myfun gets executed afler every 1000 millisec,,, To break this program running in a loop we have to press controle, EX cattbacks What is callbacks 7 Callbacks is a function which is usually passed as an argument to another function ang usually invoked after some kind of event, How it works ? The callback function is passed as an argument to another function. When particular e\. ‘oceurs then only it is invoked, By the time callback function is executing another task gets executed. Hence execution of callbacks is asynchronous execution, Example Code ‘Step 1 : Create a simple text file named “myfile.txt” as follows - myfile.txt ‘Bow are you? % : ack and Jil went up the hill, wo fetch a glass of water Step 2 : Create a JavaScript file(s) that contains the callback function callbackDemo,js var fs = require(‘is'); console log("Serving User!") fsreadFile(myfile tx, function (err, data) { if (err) return console.error(err); ‘console.log(“*** Contents of the File are ‘console log(data toString()); yh wonsole.log("Serving User2"); - (console log("Serving Users"); onsoleJog("Good Bye!lI"); Output JiNodeISExamiples>node calibackDemo|je) TECHNICAL PUBLICATIONS® » an up-thrus for knowedgeFull Stack Web Dovelopment 2-2 *** Contents of thie File are. How are you? Jack and Jill went up the hill, to fetch a glass of water gram xplanation : In above program. 1) We have to read a file named myfile.tet, but while reading a file it should not block the execution of other statements. hence a call back function is called in which the file is read. 2) By the time file gets read, the remaining two console functions indicating “Serving user 1 read in the buffer, then those contents of the file are displayed on the console. GEVEMae ree 1. Explain the callbacks in node js with suitable example. nd “Serving user 2” are not blocked. rather they are executed, once the contents are Handling Data /0. PAU Buffers * Buffer is class that allows us to store raw data similar to arrays. * Ibis basically a class that provides the instances for storing the data. It isa global class so we can use it without any need of importing a buffer module. Creation of Buffer Creating a butter is very simple. For example ‘var butler = new Buffer(10); This will create a buffer of 10 units. Similarly we can create a buffer as follows - var buffer = new Buffer([1,2,3,4,5],"utf8"); The second parameter which we have passed here is encoding scheme. It allows various is default one), ascii,ucs2,base64, or hex. Writing to Buffer The syntax for writing to the buffer is \write(stringl,offset},{,Jength||,encoding]) encodings such as utf8(thi TECHNICAL PUBLICATIONS? - an up-thrust for knowiedgeFull Stack Web Development 2-26 Full Stack Web Development 228 ry where string : It is the string to be written to the buffer. offset : It is the index from where we can start writing. The default value is 0. length : It indicates the number of bytes to be written to the buffer. Encoding : It indicates the desired encoding. The default one is “ut Example Code Following is a simple node js program that shows how to write data to the buffer. BufferExample.js Program Explanation : In above program, ‘We have used write method for writing to the buffer. For displaying the string written to the buffer we have to use toString method along with the encoding scheme. Reading from Buffer ‘i ling from buffer is as follows - a, encoding : It indicates the encoding scheme. The default one is “utf8”. start : Beginning index is indicated by this value. The default is 0. end : Ending index is indicated by this value. ETH streams Stream can be defined as objects that reads data from source or writes the data to t* destination in continuous fashion. TECHNICAL PUBLICATIONS® - an up-thus for knowledge _—_d