0% found this document useful (0 votes)
470 views

FSWD Tech Pub

full stack web development notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
470 views

FSWD Tech Pub

full stack web development notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 232
FULL STACK WEB DEVELOPMENT Subject Code : IT3501 Semester - V (Information Technology) © Copyright with Author All publishing rights (printed and ebook version} reserved with Technical Publications. No part of this book should be reproduced in ony form, Electronic, Mechanical, Photocopy or any information storage and retrieval system without prior permission in writing, from Technical Publications, Pune, Published by = TECHNICAL! Amit Residency, Office No.1, 412, Shoniwar Peth, = PUBLIEATIONS | °° - 4! 1030, MS. INDIA, Ph.: +91.020-24495496/97 (cum _Aupninsirtonsie ) Emoil : [email protected] Website : www:technicalpublcotions Printer : Yogiraj Printers & Binders S.No. 10/1A, ‘Ghule Industrial Estate, Nanded Vilage Road, Tal - Havel, Dit Pane - 411041 ISHN 978.03-8885-398-0, Nl 9789355853950 [1),PREFACE The importance of Full Stack Web Development is well known in various engineering fields. Overwhelming response to my books on various subjects inspired me to write this book. The book is structured to cover the key aspects of the subject Full Stack Web Development. ‘The book uses plain, lucid language to explain fundamentals of this subject. The book provides logical method of explaining various complicated concepts and stepwise methods to explain the important topics. Each chapter is well supported with necessary illustrations, practical examples and solved problems. All the chapters in the book are arranged in a proper sequence that permits each topic to build upon earlier studies. All care has been taken to make students comfortable in understanding the basic concepts of the subject Representative questions have been added at the end of section to help the students in picking important points from that section. The book not only covers the entire scope of the subject but explains the philosophy of the subject. This makes the understanding of this subject more clear and makes it more interesting. The book will be very useful not only to the students but also to the subject teachers. The students have to omit nothing and possibly have to cover nothing more. I wish to express my profound thanks to all those who helped in making this book a reality. Much needed moral support and encouragement is provided on numerous occasions by my whole family. I wish to thank the Publisher and the entire team of Technical Publications who have taken immense pain to get this book in time with quality printing. Any suggestion for the improvement of the book will be acknowledged and well appreciated, Author Ms. A.A. Pantambekar Dedicated to God. «i.= SYLLABUS Full Stack Web Development - (IT3501) UNITI —_ BASICS OF FULL STACK Understanding the Basic Web Development Framework - User - Browser - Webserver - Backend Services - MVC Architecture - Understanding the different stacks -The role of Express - Angular ~ Node - Mongo DB - React. (Chapter - 1) UNITIT = NODEJS. Basics of Node JS - Installation - Working with Node packages - Using Node package manager - Creating a simple Node,js application - Using Events ~ Listeners - Timers - Callbacks - Handling Data /O - Implementing HTTP services in Nodejs. (Chapter - 2) UNITIIT ~=MONGO DB 7 Understanding NoSQL and MongoDB - Building MongoDB Environment - User accounts - Access control - Administering databases - Managing collections - Connecting to MongoDB from Node,js - simple applications. (Chapter - 3) UNITIV EXPRESS AND ANGULAR Implementing Express in Node.js - Configuring routes - Using Request and Response objects - Angular - Typescript - Angular Components - Expressions - Data binding - Built-in direct (Chapter - 4) UNIT V REACT MERN STACK - Basic React applications - React Components - React State - Express REST APIs - Modularization and Webpack - Routing with React Router - Server-side rendering. (Chapter - 5) wy)TABLE OF CONTENTS Chapter-1 Basics of Full Stack (1-1) to (1 - 14) 1.1 Understanding the Basic Web Development Framework... 1-2 1.2 User. 1-3 1.3 Browser... 1-3 1.4 Web Server 1-5 1.4.1 Apache. 1-5 14.2 IIS. 1-6 1.5 Backend Services. 1-6 1.6 MVCArchitecture 1-7 1.6.1 MVCin Practical 1-8 1.7 Understanding the Different Stacks 1-8 1.7.1 Express... 1.7.2. Angular... 173 Node... 1.7.4 MongoDB 175 1.8 Two Marks Questions with Answers LUN ee Chapter-2 | NODEJS (2-1) to (2 - 48) 2.1 Basics of Node JS. 2.2 Installation. 2.3 Working with Node Packages... 2.4 Using Node Package Manager. 2.4.1 _ Installing Node Packages Modules.. 2.4.2 Using package.json(Use of npm init).. “as 26 27 28 23 2.10 241 2.12 Two Marks Questions with Answers .. 2.4.3 Node,js Built in Module: Creating a Simple Node,js Application. Using Events. 2.6.1 Concept of Event Loo} Listeners Timers Callbacks. Handling Data 1/0. 2.10.1 Buffers. 2.10.2 Streams... 2.10.3 File System Implementing HTTP Services in Node: 2.11.1 URL Object. 2.11.2 Query String and Form Parameters . 2.11.3 Request, Response and Server Object.. 2.11.3.1 The http ClientRequest Object. 2.1.3.2 The ServerResponse Object. 2.1.3.3 The incomingMessage Object. 2.11.3.4 The http Server Object. Chapter-3 MONGO DB 3a 3.2 3.3 Understanding NoSQL and MongoDB... 3.11 NOSQL..... 3.1.2 MongoDB... Building MongoDB Environment. User Accounts. 3.3.1 Listing Users 3.3.2 Create User Accounts... 3.3.3. Remove Users. wi)3.4 Access Control... 3-17 3.4.1 Creating a User Administrator Account 3-17 3.4.2 Creating Database Administrator Account sn 3 219 3-19 - 3-20 3.5 Data Types in MongoDB 3.6 Administering Databases... 3.7 Managing Collections... woe 3-22, 3-29 3-30 3.8 Connecting to MongoDB from Node. js 3.9 Understanding the Objects Used in MongoDB Node js Driver 3.10 Simple Applications. 3.11 Advanced MongoDB. 3.11.1 Indexin 3.11.2 Aggregation. 3.11.3 Map Reduce 3-31 3-41 we 341 3-46 3.12 Two Marks Questions with Answers 3-48 Ut eg Chapter-4 — Express and Angular (4-1) to (4- 66) 4.1 _ Implementing Express in Node, 4.1.1 Installing Express. 4.2 Configuring Routes... 4.3. Using Request and Response Objects... 4.4 Introduction to TypeScript .. 4.4.1 _Installatior 4.4.2 How to Write TypeScript Program ? 45 Type Annotations . 4.6 Variables and Constants... 4.7 Understanding Interfaces 4.8 Implementing Classes. 4,9 Implementing Modules 4.10. Understanding Functions 4.11. Basics of Angular (wi)442 4.13 414 4.15 4.16 4.17 4.18 4.19 Angular CLL Creating First Application in Anguler. 4.13.1 Angular Lifecycle. 4.13.2. Understanding and Using neModule . Angular Architecture... ‘Angular Components. Expressions... 4.16.1 Pipes.. Data Binding. Built-in Directives 4.18.1 Structural Directives 418.1. nglf Directive... 4,18.1.2 ngfor Directive. 4.18.1. ngSwitch Directive 4.18.2 Attribute Directives ‘Two Marks Questions with Answers. Chapter-5 React (5 - 1) to (5 - 40) 5.1 5.2 53 5.4 55 5.6 57 58 59 5.10 5.11. ‘Solved Model Question Paper MERN Stack... Basic React Applications. React Components Inter Components Communication. The props. React State... Express REST APIs Modularization and Webpack Routing with React Router. Server-side Rendering ‘Two Marks Questions with Answers,UNIT I Basics of Full Stack Syllabus Understanding the Basic Web Development Framework User ~ Browser ~ Webserver ~ Backend Services - MVC Architecture - Understanding the different stacks ~ The role of Express ~ Angular - Node - Mongo DB - React Contents 1.1. Understanding the Basic Web Development Framework 1.2 User 1.3. Browser 1.4 Web Server 1.5 Backend Services 1.6 MVC Architecture 1.7 Understanding the Different Stacks 1.8 Two Marks Questions with Answers (0)Full Stack Web Development. 1-2 EE Understanding the Basic Web Development Framework What is Framework 7 + developing applications which provides a foundation on # Framework is a platform for meworks are the sofiwa which software applications can be built. The front end frar ire packages that provide ~ © The reusable code modules. © Standardized front end technologies and © Ready made interface blocks for making the front end development faster ang | simple. Basic concept : A web development framework is a collection of tools, libraries and technologies that are used 10 create web applications and websites It provides a basic structure and set of conventions for developers to build web applications quickly and efficiently. Following are some important reason which indicate why do we use web frameworks - 1. Saves time : The most striking feature of web framework is that it saves time and enei in developing any app because the developer doesn’t need to wory about session handling. error handling and authentication logic. These functions are taken care of by web frameworks | 2. Well organized app : The web framework itself takes care of managing directories and files. This makes the complete application well organized. 3, Flexibility and customizable : Add-ons, themes, plugins, widgets enable rapid customization on the web application. This brings out a lot of flexibility in code | development. \ 4, Code reusability : Framework also promotes the reuse of code. | 5, Security : Framework makes developers sure that the application uses good security measurements because the framework itself takes care of it. . | ‘The components of web development framework are - User Browser Webser 4, Backend services | | || TECHNICAL PUBLICATIONS® an upstnust for kowledgo | at |asics of Full Stack Full Stack Web Dovolopment ‘The components of web development framework are as shown below - Backend services Browser @@ Request Response () Interacts 0 0 User Fig. 1.1.1 Components of web development framework Let us discuss them one by one - fuser User is an important part of web development framework. © Users expectations from a website define the requirements for developing a good website, * Normally an efficient and easy to use website is preferred by the user. They also expect that the same website must behave closer to the applications installed on their computers and mobile devices. * User interacts with the browser by using input devices such as mouse, keyboard on PC or swipes and taps on mobile devices. The web framework processes the user input and provides the required visual output. Browser * Browser is an application for accessing websites, User interacts with the browser in the web development framework + The browser plays three roles in web framework - 1. It provides communication to and from the web server, 2. It interprets the data from the server and displa the visual output, 3. The browser handles user interaction through the keyboard, mouse, touchscreen or other input device and takes the appropriate action. TECHNICAL PUBLICATIONS® - an up-thrust for knowledgeFuill Stack Web Development 1-4 Basics of Full Stack + Browser to web server communication : © For communicating with the webserver, the browser makes use of HTTP and HTTPS protocols. © HTTP stands for HyperText Transfer Protocol. This protocol is used for communication between browser and web server. It is a request/response protocol HTTP also defines what type of requests that can be made by the user. Similarly the HTTP protocol defines the format of those requests and responses. © HTTPS protocol is similar to HTTP protocol but it adds an additional security | layer so that the user can decide whether to accept the connection or not. i o There are three types of requests to the server - i) GET : The GET request is typically used to retrieve data from the server. This data can be in the html files or images. ii) POST : The POST request is used for sending the data to the server. For example - Credit card details while performing online shopping. iii)AJAX : AJAX stands for Asynchronous JavaScript and Extensible Markup Language. In AJAX, the GET or POST request is done directly by JavaScript | running in the browser. * Difference between GET and POST requests : When a user submits his request using i the GET method then the URL string displays the request submitted by the user. But if the POST method is used then URL string does not show the submitted contents. © The common browsers are Internet Explorer, Mozilla Firefox, Google Chrome, Safari. © Rendering the bowser view : © The browser reads data from initial URL and then renders the HTML document to 1] build the Document Object Model (DOM). The DOM is a tree structured object. The browser interprets each DOM element and renders it to user's screen to build a webpage view. ° | © Browsers get different types of data from multiple web server requests to’ build the | webpage, i © Following are various types of files that are displayed by the browser - * HTML files : The HTML files represent the static data, * CSS files : These files define how the elements on the page are to be styled using fonts, colors, borders and so on. * Client side script : Normally these scripts are in JavaScript files. These scripts provide additional functionalities to the webpage, facilitate the TECHNICAL PUBLICATIONS® - an up-thrust for knowlodgaFull Stack Wob Development 1-5 ____ Basics of Full Stack, intera vity of user with the web page and provide any necessary logic required to display the page and provide the functionality * Media files : These are the files that contain images. videos and audio. These files can be rendered as webpages. * Data: Any data such as XML, JSON or raw text can be provided to the web server as a response to an AJAX request. * HTTP headers : The HTTP headers define the type of data in the request as well as the type of data expected to be returned back to the browser. User interaction : User interacts with the browser with the help of input devices such as mouse clicks, keyboards, touchscreens. The browser has an event system that captures the user events and then takes appropriate action. This action can be loading the web Page obtained from the server as a response or displaying the pop-up menu. £3 Web Server Web server is a special type of server to which the web browser submits the request of a web page which is desired by the client. There are some popularly used web servers such as Apache and IIS from Microsoft. Functions of web server Various functions of web server are - 1. 2. a 41 ‘The web servers accept the requests from the web browsers. The user request is processed by the web server. The web servers respond to the users by providing the services which they demand for over the web browsers. ‘The web servers serve the web based ap} The DNS translates the domain names into the IP addresses. The servers verify given address exists, find necessary files, run appropriate scripts, exchange cookies if necessary and return back to the browser. Some servers actively participate in session handling techniques. Apache Ic isan excellent server because of its two important features : Reliability and Efficiency. * Secondly it is more” popular because it is an open source software. That means it is freely available to anybody. Apache web server is best suitable for UNIX systems but it TECHNICAL PUBLICATIONS® - an up-thrust for knowledgeON _ Full Stack Web Development S18 Of Fults, yeb server can be configured ag \ can also be used on Windows box. The apache wel Fea figured a, \ requirements using the file httpd.conf. Ths fle is present in the Apache a | package. EEE iis The intemet information series of itemet information server is a kind of web soy. | provided by Microsoft. This server is most popular on the Windows platform, \ Following are some differences between Apache and IIS servers ~ Sr.No. Apache web server HS web server | 1. | Apache web server is useful on both unix | TIS web server is used on windows based ystems and on windows platform. platform, 2. | It isan open source product. | Itis a vemtor specific product and can be used on windows products only. 3. The Apache web server can be controlled For the IIS server, the behaviour is | by editing the configuration file iipd.conf | controlled by modifying the window based management programs called IIS snap in. We can access TIS snap-in. | J ‘hrough the Control-Panel- | >Administrative Tools EEX Backend Services Backend services are the services that run behind the web server. These services provide the data to the web server which is requested by the web b rowser, (backend service) or some other backend ser sends it back to the browser, vice retrieves the information, formats it and then Similarly, when the data comes browser tothe web Server connects tothe database and updates the dat, 1. Explain web development framework wih w the a it ; explain err ‘table block diagram, Also exp! Server in the form of request, then the web rr PUBLICATIONS on paint orinauwagaFull Stack Web Development 1-7 Basics of Full Stack WG wc Architecture ‘The MVC stands for Model, View and Controller. It is a pattern for the architectural framework. consists of three parts - 1. Model : ‘This part of the architecture is responsible for managing the application data This module responds to the request made from view. The model gives instructions to the controller to update when the response is made. 2. View : This part takes care of the presentation of data. The data is presented in desired ing JSP. ASP. PHP and so format with the help of view. This is a script based system on. 3. Controller : The controller receives input, validates it and then performs business operations that modify the state of the data user requests and performs interaction with the model. Refer Fig. 1.6.1 model. The controller basically responds to takes model data and updates view Fig. 4.6.1 MVC architecture ‘© Model represents the data. r © View is the user Interface, * Controller is the request handler. Features of MVC framework 1. Separation of logic : There is a separation of application tasks such as input logic, business logic and UI logic. This makes testing and debugging easy. Modification in one component does not affect the other 2. Ability to provide multiple views : In MVC model, we can create multiple views. 3. Faster development process : MVC supports rapid and parallel development. If an MVC model is used to develop any particular web application then it is possible that one programmer can work on the view while the other can work on the controller to create the business logic of the web application. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge— Basics of Full Stach Full Stack Web Development 1:8 | 4. Returns data without formatting : MVC pattern retums data without applying any formatting, Hence, the same components can be used and called for use with any interface. 5, Customization : It is an extensible and pluggeble framework. MVC framework are designed so that the components can be easily replaced or customized. EEGXI Mc in Practical In order to understand the analogy of MVC let us take a real life example. || Let's take the example of a restaurant. When you visit a restaurant, the waiter presents you with a menu, You view the menu and then tell the waiter your order. The waiter notes down the order and passes it to the chef, in the kitchen, The chef uses the raw materials from the refrigerator and cooks the dish. The waiter then takes the dish from the kitchen and then presents it to you, after which you can enjoy your meal. The waiter acts as a controller. | Here the menu and the food come under the view component. The chef and the refrigerator can be thought of as the model. | T. Explain MVC architecture with a suitable diagram. | 2. Enlist the features of MVC framework. Understanding the Different Stacks The stack development refers to the end to end application software development. The Node.js to angular stack consists of - MongoDB, express, angular, Node.js. The bi | | ic block diagram of how the Node,js to angular fits into the web framework model is as | shown below - i TECHNICAL PUBLICATIONS® - an up-trus for knowledgoFull Stack Web Development 1-9 Basics of Full Stack Backend services Browser t ' 1 Database ' I t IL Angut e> © Response User Fig. 1.7.1 Full stack web development framework Express Express is used for server side development in full stack. As it is running in Nodes to configure, implement and control the web application. it is easy Following are the reasons why express is a great framework to start from - 1) Routing : Express JS provides a routing mechanism so that it is possible to reach to different web pages using the URLs. 2) Brror handling : Express provides built-in error handling for documents. 3) Easy integration : Express server can easily be implemented behind an existing reverse proxy system. This allows it to be easily integrated into your existing secured system. 4) Cookies : Express provides easy cookie management. 5) Session and cache management : Express has session management and cache management facility FY Angular Angular is a client side framework developed by Google. It is written in TypeScript. angular provides all the functionalities needed to handle user input in the browser, manipulate data on the client side. It also controls how elements are displayed in the browser window. TECHNICAL PUBLICATIONS® - an up-thrust for knowledgeFull Stack 4 Web Development 1-10 Basics off Following are the reasons why angular is a great framework to start from - y 2) 3) 4) The Clean : Using angular the developer can develop clean and logical code Extensibility : The angular allows to extend almost every aspect of the tanga provide the custom implementation. Reusable Code : Using angular the reusable code can be written. Data binding : mechanism. sing angular the data ean be bound to HTML elements using the seo. Support : As the angular framework is developed by Google, there exists a great support for developing the web applications. Compatibility : Angular is based on TypeScript. Hence it is easy to integrate angul la into the working environment. Node Node.js is a development framework that uses Google’s V8 JavaScript engine. The ‘meaning of V8 JavaScript engine is that it parses and executes the JavaScript code. The Node,js code is written in JavaScript and then compiled. Following are the reasons why Nodes is a great framework to start from - y 2) 3) 4) 5) Easy to use : Node,js is very much easy to set up. Developing the web applications using Nodejs is also very easy. Extensibility : New modules that are required to extend the Node,js functionality ean Ba, developed at any time, Event driven scalabi In Node,js, the web requests are processed on the same thread using basic event model. Nodejs uses a single thread model with event looping. Similarly the non blocking response of Node.js makes it highly scalable to serve large number of requests. Efficient : The Node,js is built on V8 JavaScript engine and it is very fast in code execution, Use of JavaScript, end-to-end : The one of the important reasons of using Node,js is that it allows to write both server and client side scripts i JavaScript. This makes easier to work for client side developers as well as for server side developers. MongoDB MongoDB is a part of backend services. It is basically a scalable NoSQL database. The data is stored in the form of a JSON object. TECHNICAL PUBLICATIONS® - an up-thrust for knowtodgeFull Stack Web Development tet Basics of Full Stack Following are the reasons why MongoDB is a great framework to start from - 1) Document orientation : The data is stored in the document form in the MongoDB 2) High performance : It is the highest performing database. 3) High scalability : The MongoDB allows horizontal scalability by sharing data across multiple servers. 4) High availability : MongoDB provides high availability and redundancy with the help of replication. That means it creates multiple copi different server so that if one server fails, then the data is retrieved from another server. s of the data and sends these copies to a ReactIS is an open source, component-based front end JavaScript library maintained by facebook, This library is responsible only for the view layer of the application, That means this JavaScript is for building user interfaces. Following are the reasons why MongoDB is a great framework to start from - 1) Virtual DOM : DOM stands for Document Object Model. It also provides a way to update the content, structure and style of the document. Virtual DOM is a representation of the original DOM. When a user updates something on the web application, DOM gets updated. Updating the DOM whole DOM which makes it slower. But actually there is no need to update the whole DOM, instead, these frameworks should update only the part of DOM that is required to update. This is what the virtual DOM does. This is why ReacUS’s DOM manipulation is much faster than other frameworks, Due to this property, whenever any change is made in the web application, then those changes are reflected on the web page within no time, very slow, most of the JavaScript frameworks update the 2) Components : This feature allows the web developer to create custom elements which can be reused in HTML. 3) JSX : JSX is an extension of JavaScript syntax. JSX can be seen as a combination of Javascript and XML. The syntax of JSX is very simple that makes writing components very easy. 4) One way data binding : The ReactIS is designed in such a way that it follows, unidirectional or one way data binding. That means, data is allowed to flow in one direction at a time. This helps in achieving greater control over the application. This makes helps in increasing the efficiency of an application, TECHNICAL PUBLICATIONS® - an up-thrust for knowledge7 Ba 5 Full Stack Web Development 1-12 ISICS Of Full Sta, eeu 1. Explain the use of Node.js in full stack development. ] 2. Write short note on - MongoDB. 3. Give the reasons - Why is express useful in web frameworks ? 4, Explain the role of react in web framework. EE] Two Marks Questions with Answers Q.1 What is web development framework ? Ans. : ‘+ A web development framework is a collection of tools, libraries and technologies that are used to create web applications and websites. * It provides a basic structure and set of conventions for developers to build web applications quickly and efficiently Q.2 Why do we use web framework ? Give any two reasons, Ans. : 1. Saves time : The most striking feature of web framework is that it saves time and energy in developing any app because the developer doesn’t need to worry about session handling, error handling and authentication logic. These functions are taken care of by web frameworks, 2. Flexibility and customizable : Add-ons, themes, plugins, widgets enable = customization on the web application, This brings out a lot of flexibility in code’ development .3 What are the components of web development framework ? ‘Ans. : The components of web development framework are — (1) User (2) Browser (3) Web Server (4) Backend services Q.4 Give the importance of browser Ans. : The browser plays three roles in web framework - 1. It provides communication to and from the web server. 2. It interprets the data from the server and displays the visual output. 3. The browser handles user interaction through the keyboard, mouse, touchscreen or other input device and takes the appropriate action, TECHNICAL PUBLICATIONS® - an up-thrust for nowiedgeFull Stack Web Development 1-13 Basics of Full Stack Q.5 What Is GET and POST request ? Ans. : 1) GET : The GET request is typically used to retrieve data from the server. This data can be in the .him! files or images. ii) POST : The POST request is used for sending the data to the server. For example - Credit card details while performing online shopping. Q.6 What is web server ? ‘Ans. ; Web server is a special type’of server to which the web browser submits the request of a web page which is desired by the client. Q7 Enlist the functions of web server ‘Ans. : Various functions of web server are - 1. The web servers accept the requests from the web browsers. 2. The user request is processed by the web server. 3. The web servers respond to the users by providing the services which they demand for over the web browsers. 4, The web servers serve the web based applications. Q.8 What do you mean by backend services Ans. 1) Backend services are the services that run behind the web server. These services provide the data to the web server which is requested by the web browser. 2) The most commonly used backend service is a database that stores the information. Q.9 What is MVC 7 Ans. : 1. Model : This part of the architecture is responsible for managing the application data. This module responds to the request made from view. The model gives instructions to the controller to update when the response is made. 2. View : This part takes care of the presentation of data The data is presented in desired format with the help of view. This is a script based system using JSP, ASP, PHP and so on. 3. Controller : The controller receives input, validates it and then performs business operations that modify the state of the data model, The controller basically responds to user requests and performs interaction with the model. TECHNICAL PUBLICATIONS® - an up-thrust for knowledgeFull Stack Web Development 4-14 Basics of Full Stncn Q.10 What is full stack 7 Ans. Full stack development is development of both front end and back end of any wel application, The fall stack consists of - 1. MongoDB 2. Express 3. AngularJS 4. Node,js_ 5. Reaet.js Qou ay TECHNICAL PUBLICATIONS®. an uptnust for knowodge :UNIT II NODE JS Syllabus Basics of Node JS - Installation - Working with Node packages - Using Node package manager - Creating a simple Node,js application - Using Events Listeners - Timers ~ Callbacks - Handling Data 1/0 - Inplementing HTTP services in Nodejs Contents 2.1 Basics of Node JS 2.2 installation 2.3 Working with Node Packages 24 Using Node Package Manager 2.5 Creating a Simple Node.js Application 2.6 Using Events 27 Listeners 2.8 Timers 2.9 Callbacks 2.10 Handling Data YO 2.11 Implementing HTTP Services in Node,js 2.12 Two Marks Questions with Answers eHFull Stack Web Development 2-2 ____ Non El Basics of Node JS * Node JS is an open source technology for server. * Using Node,js we can run JavaScript on server. © Itnuns on various platform such as Windows, Linux, Unix, and MacOS. Uses of Node,js It can perform various tasks such as - 1) Itcan create, open, read, delete, write and close files on the server. 2) Itcan collect form data. 3) It can also add, delete, modify data in databases. 4) It generate dynamic web pages. Features Following are some remarkable features of node,js - 1) Non blocking thread execution : Non blocking means while we are waiting for a response for something during our execution of tasks, we can continue executing the f next tasks in the stack. 2) Efficient : The node.js is built on V8 JavaScript engine and it is very fast in code execution, 3) Open source packages : The Node community is enormous and the number of permissive open source projects available to help in developing your application in’ | much faster manner. 4) No buffering : The Node.js applications never buffer the data. | 5) Single threaded and highly scalable : Node,js uses a single thread model with event | looping. Similarly the non blocking response of Node,js makes it highly scalable to | sever large number of requests. | J. What is Node,js ? Enlist the features of Node js. | stallation 1] @ For executing the Node.js scripts we need to install it. We can get it downloaded from | hutps://nodejs.org/en. | _ TECHNICAL PUBLICATIONS® «an up-tneut for knowledgeFul Stack Web Davatopment 268 NODE JS. © The installation can be done on Linux or Windows OS. It has very simple installation procedure New security releases now available for 15.«, 14.*, 12. and 10.x Download pe Souler) Download node MSI for windows by clicking on 14.16.0 LTS or 15.1.0 Current button. © Afier you download the MSI, double-click on it to start the installation as shown below Welcome to the Node.js Setup Wizard TECHNICAL PUBLICATIONS? - an up-inrust for knowledgeFull Stack Web Development 2-4 __NODE ys ff oF | * Click Next button to read and accept the License Agreement and then click Install. j () | will install Nodejs quickly on your computer. Finally, click finish to complete the | | installation. Hut © Verify Installation | ‘© In order to verify the installation we have to open a command prompt and type the | following command - | BEE Command Prompt — 7o “ix | >node -v | jvaa.35.4 | 1D:\> | i | | * If the node,js is successfully installed, then some version number of the node,js which {| you have installed in your PC will be displayed. | * Afier successful installation we can now execute the Node,js document. The Nodejs file jill has extension js. i * Following is a simple node.js program which can be written in notepad. i app.js | ‘console.log(*Welcome to first Nodejs Application program’), i | Output \ il BI Command Prompt - oc ii :\>node app. 3s f i (elcome to first Node.js Application program | | Va TECHNICAL PUBLICATIONS® - an up-thast for knowledgeull Stack Web Development 2-5 NODE JS BJ Working with Node Packages © A node packaged module is a packaged library that can be easily shared, reused and installed in different projects. © The node packages include a package.json file that defines the packages. © The package,json is an important file of any node project. It records the important metadata about a project. The package.json file consists of - © name: The name of the application/project. version : The version of application. The version should follow semantic versioning rules. ; © description : The description about the application, purpose of the application, technology used like React, MongoDB, etc: © main : This is the entry/starting point of the app. It specifies the main file of the application that triggers when the application starts. Application can be started using npm start. © scripts : The scripts which need to be included in the application to run properly. © engines : The versions of the node and npm used. These versions are specified in case the application is deployed on cloud like heroku or google-cloud. © keywords : It specifies the array of strings that characterizes the application. author : It consists of the information about the author like name, email and other author related information. © license : The license to which the application confirms is mentioned in this key-value pair. EZ] using Node Package Manager © A package in Node,js contains all the files you need fora module. © Modules are JavaScript libraries you can include in your project. © The NPM stands for node package manager. © NPM consists of two main parts : 1) A CLI (command-line interface) tool for publishing and downloading packages, 2) An online repository that hosts JavaScript packages. © NPM gets installed along with the installation of node.js. To verily the presence of npm package on your machine install following command - TECHNICAL PUBLICATIONS? - an up-to knowledgeFull Stack Web Development 2-6 IEE C\Windows\system32\cmd.exe : \Wode3SExamplesonpm -~version 14.18 : \NodeISExamples> ¢ There are various command line options that npm uses, These options are as follow: Option Purpose Example install | installs the packages either using a package.json or from the repository or from a local location. | ‘mpm install express. rpm install. rch | Searches the module packages in the repository. ‘pm search express, | packages. 4s + List all the users who have access to modify @ package and push new versions. | Handy when you need to know who to bug for help. add : Add a new user as a maintainer of a package. This user is enabled to modify metadata, publish new versions and add other owners. rm : Remove a user from the package owner list. This immediately revokes their privileges. install-g | Installs the package globally. ‘npm install express -g. remove Removes the specific module. npm remove express. View Displays the module details. npm view express. Publish Publishes the module defined by a mpm publish, | package,json file to registry. unpublish | Unpublished the module which is published | npm unpublish testModule, already. ‘Owner [Manages the ownership of published | npm owner add npm owner rm pm owner Is TECHNICAL PUBLICATIONS® - an up-tirust for knowsodgeFull Stack Wob Development 2-7 BERD installing Node Packages Modules © For installing any node,js module we have to use th Ba C\Windows\ stem 32rd exe ): \WodeISExaxplesonpa install express —— Issue this command created 9 lockfile as package-lock.json. You should comeit this file. ‘[email protected] No repository field. [email protected] \dded 50 packages from 37 contributors and audited 50 packages in 4.9693 found ©) vulnerabilities ): WodeISExaxples., * As soon as we issue this command the package-lock file gets generated in the current folder. * Forusing this module in our program we have to use following command - Wvar ex = require(‘express'}; Example of using the existing module Step 1: We will install the module upper-case by issuing the install command BBY CAWindows\systemaz\emd exe - a x] et Beoderstxomplesonm instal vper-cate ‘[email protected] No repository field. | | } ls upper-case62.0.2 | hndded 2 packages fron 2 contributors and audited 52 packages in 4.0875 | | found 0 vulnerabilities D:\WodeIsexanples> TECHNICAL PUBLICATIONS® - an uptnrst for knowledge7 Full Stack Web Development 2-8 ‘Full Stack Web Development © 2-8 Step 2: You can locate this module inside your folder/node_modules. Now’ open jy, suitable text editor and write node js script that makes use of this module, moduleDemojs “var upp_ch = require(upper-case); console.log(upp_ch.upperCase( am proud of you')); x Output BB CAWindons\system32\emdexe - Go xX ): \NodeISExomples> EEE] using package.json(Use of npm init) © We can create our own package using following steps Step 1 : Create a sample folder. Open command prompt and go to that directory location, For instance - | have created a folder named nodejsexamples. Issue the command npm init at the command prompt. : 1, Boor pscrosort wanton {Verston’s0.R aoe e68) z ays] ie ‘2620 Microsoft Corporation. All rights reserved, Wade SEramplesorpe init | this wtitity will velk you through creating a package. json file. it only covers the most common iteas, and tries to purse sensible defoults. “nom help init” for definitive docueentetion on these fields i wractly what they do, psc “ne install

” 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

You might also like