Paidiblog825102560.files.wordpress.com



3.1. Introduction:Why TypeScript is developed while having JavaScript? When JavaScript was developed then JavaScript development team introduced JavaScript as a client-side programming language. But when people was using JavaScript then developer get to know that JavaScript can be used as a server-side programming language also. But When JavaScript was growing then the code of JavaScript became complex and heavy. Because of this, JavaScript was even not able to full fill the requirement of Object-oriented programming language. This prevents JavaScript from succeeding at the enterprise level as a server-side technology. Then TypeScript was developed by the development team to bridge this gap.3.1.1 What is Typescript?By definition, “TypeScript is JavaScript for application-scale development.”TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.3.1.2 Features of TypeScript:TypeScript Code is converted into Plain JavaScript Code:: TypeScript code is not understandable by the browsers. That’s why if the code is written in TypeScript then it is compiled and converted the code i.e. translate the code into JavaScript. The above process is known as Trans-piled. By the help of JavaScript code, browsers are able to read the code and display.JavaScript is TypeScript: Whatever code is written in JavaScript can be converted to TypeScript by changing the extension from .js to .ts.Use TypeScript anywhere: TypeScript code can be run on any browser, devices or in any operating system. TypeScipt is not specific to any Virtual-machine etc.TypeScript supports JS libraries: With TypeScript, developers can use existing JavaScript code, incorporate popular JavaScript libraries, and can be called from other JavaScript code. Difference between TypeScript and JavaScript:TypesScript is known as Object oriented programming language whereas JavaScript is a scripting language.TypeScript has a feature known as Static typing but JavaScript does not have this feature.TypeScript gives support for modules whereas JavaScript does not support modules.TypeScript has Interface but JavaScript does not have Interface.TypeScript support optional parameter function but JavaScript does not support optional parameter function.Advantages of using TypeScript over JavaScriptTypeScript always point out the compilation errors at the time of development only. Because of this at the run-time the chance of getting errors are very less whereas JavaScript is an interpreted language.TypeScript has a feature which is strongly-typed or supports static typing. That means Static typing allows for checking type correctness at compile time. This is not available in JavaScript.TypeScript is nothing but JavaScript and some additional features i.e. ES6 features. It may not be supported in your target browser but TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 also.Disadvantages of using TypeScript over JavaScriptGenerally TypeScript takes time to compile the code.TypeScript does not support abstract classes.Typescript is an Open Source technology. It can run on any browser, any host, and any OS. You will need the following tools to write and test a Typescript program ?(i)A Text EditorThe text editor helps you to write your source code. Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors used may vary with Operating Systems.The source files are typically named with the extension .ts(ii) The TypeScript CompilerThe TypeScript compiler is itself a .ts file compiled down to JavaScript (.js) file. The TSC (TypeScript Compiler) is a source-to-source compiler (transcompiler / transpiler).The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC produces an equivalent JavaScript source code from the Typescript file given as an input to it. This process is termed as transpilation.However, the compiler rejects any raw JavaScript file passed to it. The compiler deals with only .ts or .d.ts files.3.2 Compile and Execute a TypeScript ProgramLet us see how to compile and execute a TypeScript program using Visual Studio Code. Follow the steps given below ?Step 1 ? Save the file with .ts extension. We shall save the file as Test.ts. The code editor marks errors in the code, if any, while you save it.Step 2 ? Right-click the TypeScript file under the Working Files option in VS Code’s Explore Pane. Select Open in Command Prompt option.Step 3 ? To compile the file use the following command on the terminal window.tsc Test.tsStep 4 ? The file is compiled to Test.js. To run the program written, type the following in the terminal.node Test.js3.3.tsconfig.jsonThe presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways:Using tsconfig.jsonBy invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.By invoking tsc with no input files and a --project (or just -p) command line option that specifies the path of a directory containing a tsconfig.json file, or a path to a valid .json file containing the configurations.When input files are specified on the command line, tsconfig.json files are ignored.3.4 Compiler Flags(Compiler Options)Compiler flags enable you to change the behavior of the compiler during compilation. Each compiler flag exposes a setting that allows you to change how the compiler behaves.The following table lists some common flags associated with the TSC compiler. A typical command-line usage uses some or all switches.S.piler flag & Description1.--help : Displays the help manual2.--module: Load external modules3.--target: Set the target ECMA version4.--declaration: Generates an additional .d.ts file5.--removeComments: Removes all comments from the output file6.--out: Compile multiple files into a single output file7.--sourcemap: Generate a sourcemap (.map) files8.--module noImplicitAny: Disallows the compiler from inferring the any type9.--watch: Watch for file changes and recompile them on the fly3.5 Building blocks of TypescriptA TypeScript program is composed of ?ModulesFunctionsVariablesStatements and ExpressionsCommentsThe Type System represents the different types of values supported by the language. The Type System checks the validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. The Type System further allows for richer code hinting and automated documentation too.3.5.1 Data typesTypeScript provides data types as a part of its optional Type System. The data type classification is as given below ?The Any typeThe any data type is the super type of all types in TypeScript. It denotes a dynamic type. Using the any type is equivalent to opting out of type checking for a variable.Built-in typesThe following table illustrates all the built-in types in TypeScript ?Data typeKeywordDescriptionNumberNumberDouble precision 64-bit floating point values. It can be used to represent both, integers and fractions.StringstringRepresents a sequence of Unicode charactersBooleanbooleanRepresents logical values, true and falseVoidvoidUsed on function return types to represent non-returning functionsNullnullRepresents an intentional absence of an object value.UndefinedundefinedDenotes value given to all uninitialized variablesThe type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.Ex: Var name:string =”cvr” Var name=”cvr”Var name Var name:string3.5.2 Operators:The major operators in TypeScript can be classified as ?Arithmetic operators : +,-,*,/,%(Modulus),++,--Relational operators : <,>,<=,>=,==,!=Logical operators : &&(AND), ||(OR),!(NOT)Bitwise operators : &(Bitwise AND), |, ^,~, <<,>>, >>> (Right shift with Zero)Assignment operators : =, +=, -+,/+.*=Ternary/conditional operator : ?: (Test ? expr1 : expr2)String operator : Concatenation operator (+)Type Operator : typeof. It is a unary operator. This operator returns the data type of the operandEx: var num = 12 console.log(typeof num); //output: number3.5.3 Control Structures:1.Decision Making Statements :S.No.Statement & Description1.if statement An ‘if’ statement consists of a Boolean expression followed by one or more statements. if(boolean_expression) { // statement(s) will execute if the boolean expression is true } 2.if...else statement An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the Boolean expression is false.if(boolean_expression) { // statement(s) will execute if the boolean expression is true} else { // statement(s) will execute if the boolean expression is false }3.else…if and nested if statements You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).if (boolean_expression1) { //statements if the expression1 evaluates to true } else if (boolean_expression2) { //statements if the expression2 evaluates to true } else { //statements if both expression1 and expression2 result to false }4.switch statement A ‘switch’ statement allows a variable to be tested against a list of values.switch(variable_expression) { case constant_expr1: { //statements; break; } case constant_expr2: { //statements; break; } default: { //statements; break; } }2. Loopsfor loop : The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as below ?Syntaxfor (initial_count_value; termination-condition; step) {//statements }while loop : The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.Syntax: while(condition) { // statements if the condition is true }do-while loop : The do…while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. However, the condition is evaluated for the subsequent iterations. In other words, the code block will be executed at least once in a do…while loop.Syntax: do { //statements } while(condition)3. break : The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Its syntax is as follows ?Syntaxbreak 4. continue : The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue doesn’t exit the loop. It terminates the current iteration and starts the subsequent iteration.Syntaxcontinue3.6 FunctionsFunctions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code.A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.function function_name(param1 [:datatype], ( param2 [:datatype]):return_type { // function body return value;}Types of Parameters:Optional Parameters : Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. function function_name (param1[:type], param2[:type], param3[:type]){}Rest Parameters : Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter. function function_name (param1[:type], param2[:type],… param3[:type[]]){ }Default Parameters: Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.function function_name(param1[:type],param2[:type] = default_value) { }3.6.2 Lambda FunctionsLambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.Lambda Function – Anatomy( [param1, parma2,…param n] )=>statement;There are 3 parts to a Lambda function ?Parameters ? A function may optionally have parametersThe fat arrow notation/lambda notation (=>) ? It is also called as the goes to operatorStatements ? represent the function’s instruction set Ex:Var f =(x)=>x*xconsole.log(f(10))3.6.3 Function OverloadsFunctions have the capability to operate differently on the basis of the input provided to them. In other words, a program can have multiple methods with the same name with different implementation. This mechanism is termed as Function Overloading. TypeScript provides support for function overloading.To overload a function in TypeScript, you need to follow the steps given below ?Step 1 ? Declare multiple functions with the same name but different function signature. Function signature includes the following.The data type of the parameterfunction disp(string):void; function disp(number):void;The number of parametersfunction disp(n1:number):void; function disp(x:number,y:number):void;The sequence of parametersfunction disp(n1:number,s1:string):void; function disp(s:string,n:number):void;Note ? The function signature doesn’t include the function’s return type.Step 2 ? The declaration must be followed by the function definition. The parameter types should be set to any if the parameter types differ during overload. Additionally, for case b explained above, you may consider marking one or more parameters as optional during the function definition.Step 3 ? Finally, you must invoke the function to make it functional.ExampleLet us now take a look at the following example code ?function disp(s1:string):void; function disp(n1:number,s1:string):void; function disp(x:any,y?:any):void { console.log(x); console.log(y); } disp("abc") disp(1,"xyz");The first two lines depict the function overload declaration. The function has two overloads ?Function that accepts a single string parameter.Function that accepts two values of type number and string respectively.The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here.The overloaded function is invoked by the last two statements.On compiling, it will generate following JavaScript code ?//Generated by typescript 1.8.10function disp(x, y) { console.log(x); console.log(y);}disp("abc");disp(1, "xyz");3.7.TypeScript - ClassIn object-oriented programming languages like Java and C#, classes are the fundamental entities used to create reusable components. Functionalities are passed down to classes and objects are created from classes. However, until ECMAScript 6 (also known as ECMAScript 2015), this was not the case with JavaScript. JavaScript has been primarily a functional programming language where inheritance is prototype-based. Functions are used to build reusable components. In ECMAScript 6, object-oriented class based approach was introduced. TypeScript introduced classes to avail the benefit of object-oriented techniques like encapsulation and abstraction. The class in TypeScript is compiled to plain JavaScript functions by the TypeScript compiler to work across platforms and browsers. A class can include the following:ConstructorPropertiesMethodsThe following is an example of a class in TypeScript:Example: Classclass Employee { empCode: number; empName: string; constructor(code: number, name: string) { this.empName = name; this.empCode = code; } getSalary() : number { return 10000; }}The TypeScript compiler will convert the above class to the following JavaScript code using closure:var Employee = /** @class */ (function () { function Employee(name, code) { this.empName = name; this.empCode = code; } Employee.prototype.getSalary = function () { return 10000; }; return Employee;}());Constructor The constructor is a special type of method which is called when creating an object. In TypeScript, the constructor method is always defined with the name "constructor". Example: Constructorclass Employee { empCode: number; empName: string; constructor(empcode: number, name: string ) { this.empCode = empcode; this.name = name; }}3.8 Modules Modules helps you segmenting your application. Indeed, modules allows you to create small units of independent and reusable code. Plus, modules know their dependencies, so they can load them when needed in the right orderIn TypeScript, a module is a file containing values, functions or classes. You can make some of them public, i.e. visible from other modules, by exporting them. Non exported objects are private.Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.Exporting a declarationAny declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.Shape.tsclass shape { function draw(){ console.log(“Inside shape” } }export shapemain.tsimport shapeclass main {}3.9. InheritanceJust like object-oriented languages such as Java and C#, TypeScript classes can be extended to create new classes with inheritance, using the keyword extends.Example: Inheritanceclass Person { name: string; constructor(name: string) { this.name = name; }}class Employee extends Person { empCode: number; constructor(empcode: number, name:string) { super(name); this.empCode = empcode; } displayName():void { console.log("Name = " + this.name + ", Employee Code = " + this.empCode); }}let emp = new Employee(100, "Bill");emp.displayName(); // Name = Bill, Employee Code = 100The constructor of the Employee class initializes its own members as well as the parent class's properties using a special keyword 'super'. The super keyword is used to call the parent constructor and passes the property values. 3.9.1 TypeScript - InterfaceInterface is a structure that defines the contract in your application. It defines the syntax for classes to follow. Classes that are derived from an interface must follow the structure provided by their interface.The TypeScript compiler does not convert interface to JavaScript. It uses interface for type checking. This is also known as "duck typing" or "structural subtyping".One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function. Example: Interfaceinterface IEmployee { empCode: number; empName: string; getSalary: (number) => number; // arrow function getManagerName(number): string; }interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Ajay", lastName:"Laddha", sayHi: ():string =>{return "Hi"} } console.log("Customer Object Details: ");console.log(customer.sayHi()); console.log(customer.firstName); console.log(customer.lastName); var employee:IPerson = { firstName:"Vikas", lastName:"Jainer", sayHi: ():string =>{return "Hello"} } console.log("Employee Object Details: ");console.log(employee.sayHi());console.log(employee.firstName);console.log(employee.lastName);Interfaces have zero runtime JS impact. There is a lot of power in TypeScript interfaces to declare the structure of variables.The following two are equivalent declarations, the first uses an inline annotation, the second uses an interface:// Sample Adeclare var myPoint: { x: number; y: number; };// Sample Binterface Point { x: number; y: number;}declare var myPoint: Point;3.10 GenericsWith generics, TypeScript enables you to write code that can act on a variety of data types instead of being limited to a single one.Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type. So, components can be called or used with a variety of data types.While using any is certainly generic in that it will cause the function to accept any and all types for the type of arg, we actually are losing the information about what that type was when the function returns. If we passed in a number, the only information we have is that any type could be returned.Generics uses the type variable <T>, a special kind of variable that denotes types. The type variable remembers the type that the user provides and works with that particular type only. This is called preserving the type information.function identity<T>(arg: T): T { return arg;}The type variable T is also used to specify the type of the arguments and the return value. This means that the data type which will be specified at the time of a function call, will also be the data type of the arguments and of the return value.Generic classes have a generic type parameter list in angle brackets (<>) following the name of the class.class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T;}let myGenericNumber = new GenericNumber<number>();myGenericNumber.zeroValue = 0;myGenericNumber.add = function(x, y) { return x + y; };3.11 Decorators :With the introduction of Classes in TypeScript and ES6, there now exist certain scenarios that require additional features to support annotating or modifying classes and class members. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.It serves the purpose of adding metadata to the existing code in a declarative way.Types of decorators and its priority of execution areClass decoratorMethod DecoratorAccessor or Property DecoratorParameter Decorator?1. Class decorator:A Class Decorator is declared just before a class declaration. The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.The expression for the class decorator will be called as a function at runtime, with the constructor of the decorated class as its only argument.If the class decorator returns a value, it will replace the class declaration with the provided constructor function.The following is an example of a class decorator (@sealed) applied to the Greeter class:@sealedclass Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; }}We can define the @sealed decorator using the following function declaration:function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype);}When @sealed is executed, it will seal both the constructor and its prototype.2. Method decorators:A Method Decorator is declared just before a method declaration. The decorator is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.The expression for the method decorator will be called as a function at runtime, with the following three arguments:Either the constructor function of the class for a static member, or the prototype of the class for an instance member.The name of the member.The Property Descriptor for the member.If the method decorator returns a value, it will be used as the Property Descriptor for the method.The following is an example of a method decorator (@enumerable) applied to a method on the Greeter class:class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } @enumerable(false) greet() { return "Hello, " + this.greeting; }}We can define the @enumerable decorator using the following function declaration:function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; };}The @enumerable(false) decorator here is a decorator factory. When the @enumerable(false) decorator is called, it modifies the enumerable property of the property descriptor.3. Property DecoratorsA Property Decorator is declared just before a property declaration. Property decorators are similar to method decorators. The only difference is they do not accept property descriptor as argument and do not return anything.The expression for the property decorator will be called as a function at runtime, with the following two arguments:Either the constructor function of the class for a static member, or the prototype of the class for an instance member.The name of the member.const log = (target: Object, key: string | symbol) => {????let value = target[key];?????const getter = () =>? {????????console.log("Getting value: ", value);????????return value;????};????const setter = (val) => {????????console.log("Setting value: ", val);????????value = val;????}????Reflect.deleteProperty[key];????Reflect.defineProperty(target, key, {????????get: getter,????????set: setter????});}?class Box<T> {????@log????item: T;}?const numberInABox = new Box<number>();numberInABox.item = 12;numberInABox.item;?//Setting value: 12//Getting value: 12The log decorator above redefines the decorated property on the object.4. Parameter DecoratorsA Parameter Decorator is declared just before a parameter declaration. The parameter decorator is applied to the function for a class constructor or method declaration.The expression for the parameter decorator will be called as a function at runtime, with the following three arguments:Either the constructor function of the class for a static member, or the prototype of the class for an instance member.The name of the member.The ordinal index of the parameter in the function’s parameter list.function logParameter(target: Object, propertyName: string, index: number) { // generate metadatakey for the respective method // to hold the position of the decorated parameters const metadataKey = `log_${propertyName}_parameters`; if (Array.isArray(target[metadataKey])) { target[metadataKey].push(index); } else { target[metadataKey] = [index]; }}class Employee { greet(@logParameter message: string): string { return `hello ${message}`; }}const emp = new Employee();emp.greet('hello');In the code above, we collect all the index or position of the decorated parameters of the methods as metadata and attached to the prototype of the object.Node.js Introduction Node.js is a very powerful JavaScript-based framework/platform built on Google Chrome's JavaScript V8 Engine.It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is open source, completely free, and used by thousands of developers around the worldNode.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009.Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and 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 is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent.Features of Node.jsFollowing are some of the important features that make Node.js the first choice of software architects.Asynchronous and Event Driven ? All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a 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 the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.No Buffering ? Node.js applications never buffer any data. These applications simply output the data in chunks.Application and companies which are using Node.js.This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, LinkedIn,Wikipins, Yahoo!, and Yammer to name a few.Following are the areas where Node.js is proving itself as a perfect technology partner.I/O bound ApplicationsData Streaming ApplicationsData Intensive Real-time Applications (DIRT)JSON APIs based ApplicationsSingle Page ApplicationsNote:- The only scenario where it should not be used is if there are long processing times which is required by the application. Node is structured to be single threaded. If any application is required to carry out some long running calculations in the background. So if the server is doing some calculation, it won't be able to process any other requests. Node.js is best when processing needs less dedicated CPU time. 2 Environment SetupTo set up environment for Node.js, the following two softwares are required: (a) Text Editor and (b) The Node.js binary installables.Text EditorThis will be used to type your program. Examples of few editors include Windows Notepad, OS 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, and finally execute it.The Node.js RuntimeThe source code written in source file is simply javascript. The Node.js interpreter 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. A Node.js application consists of the following three important components ?Import required modules ? We use the require directive to load Node.js modules.Create server ? A server which will listen to client's requests similar to Apache HTTP Server.Read request and return response ? The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.var http = require('http');http.createServer(function (req, res) {??? res.writeHead(200, {'Content-Type': 'text/html'});??? res.end('<b>Hello World!<b>1');}).listen(8080); 3 Node.js Console - REPLNode.js comes with virtual environment called REPL. REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript code. To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node. It will change the prompt to > in Windows . Node.js or Node comes bundled with a REPL environment. It performs the following tasks ?Read ? Reads user's input, parses 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 the user presses ctrl-c twice.REPL can be started by simply running node on shell/console without any arguments as follows.:>nodeSimple ExpressionYou can execute various mathematical operations on REPL Node.js command prompt:> node> 1 + 34> 1 + ( 2 * 3 ) - 43>Use VariablesYou can make use variables to store values and print later like any conventional script. If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is used, then the value is stored but not printed. You can print variables using console.log().> node> x = 1010> var y = 10undefined> x + y20> console.log("Hello World")Hello WorldundefinedMultiline ExpressionNode REPL supports multiline expression similar to JavaScript. > node> var x = 0undefined> do {... x++;... console.log("x: " + x);... } while ( x < 5 );x: 1x: 2x: 3x: 4x: 5undefined>... comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions.Underscore VariableUse underscore (_) to get the last result ?$ node> var x = 10undefined> var y = 20undefined> x + y30> var sum = _undefined> console.log(sum)30undefinedNode.js REPL CommandsCommandsDescriptionctrl + cIt is used to terminate the current command.ctrl + c twiceIt terminates the node repl.ctrl + dIt terminates the node repl.up/down keysIt is used to see command history and modify previous commands.tab keysIt specifies the list of current command..helpIt specifies the list of all commands..breakIt is used to exit from multi-line expressions..clearIt is used to exit from multi-line expressions..save filenameIt saves current node repl session to a file..load filenameIt is used to load file content in current node repl session.4 Node.js Package Manager(npm)Node Package Manager provides two main functionalities:It provides online repositories for node.js packages/modules which are searchable on search.It also provides command line utility to install Node.js packages, do version management and dependency management of Node.js packages.The npm comes bundled with Node.js installables in versions after that v0.6.3.Installing Modules using NPMThere is a simple syntax to install any Node.js module ?> npm install <Module Name>For example, following is the command to install a famous Node.js web framework module called express ?> npm install expressNow you can use this module in your js file as following ?var express = require('express');5 CallbackCallbacks in the general definition are just functions that you pass to other functions. It is called at the completion of certain task.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 the APIs of Node are written in such a way that they support callbacks.Blocking Code Example:Create a text file named input.txt Create a js file named main.js with the following code ?var fs = require("fs");var data = fs.readFileSync('input.txt');console.log(data.toString());console.log("Program Ended");Now run the main.js to see the result ? > node main.jsNon-Blocking Code Example:Create a text file named input.txt Create main.js to have the following code ?var fs = require("fs");fs.readFile('input.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString());});console.log("Program Ended");Now run the main.js to see the result –> node main.jsVerify the Output.Program EndedThen the contents of the file will be printedTutorials Point is giving self learning contentto teach the world in simple and easy way!!!!!Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution.A function in NodeJS is either synchronous or asynchronous.?An asynchronous function is a function which has the functionality to call events when they complete the execution. The asynchronous function does?not wait for any task to complete, it continues its execution with next instruction.Callback function is a function which is called automatically after the completion of the execution of a time-intensive process. We can understand it by one example -? reading a text file using NodeJS. Here, we assume that the text file is big so the process of reading this file is time-consuming. So, if we are to take a normal synchronous function for reading this text file. If the file is big and takes 9-10 seconds to read this text file. Thus, this program goes into the awaited state during reading of the file. No other operation is executed during this time. This is?executed at the next instruction. So, it is called synchronous method.Now, we are to read this file using callback process or?the asynchronous method, when the program is executing, the command for reading a file does not wait for this operation to complete but it continues its execution with the next instruction. So, the program does not go into waited state or block state. Ones the file reading is completed, it automatically calls the callback function and it prints this text file content. This type of method is called the?asynchronous method.6 Events in Node.jsNode.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur. In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected.Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners .EventEmitter Class EventEmitter class lies in the events module. It is accessible via the following code ?// Import events modulevar events = require('events');// Create an eventEmitter objectvar eventEmitter = new events.EventEmitter();When an EventEmitter instance faces any error, it emits an 'error' event. When a 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.MethodsS.No.Method & Description1addListener(event, listener)Adds a listener at 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.2on(event, listener)Adds a listener at 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.3once(event, listener)Adds a one time listener to 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.4removeListener(event, listener)Removes a listener from the listener array for the specified event. Caution ? It changes the 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.5removeAllListeners([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. sockets or file streams). Returns emitter, so calls can be chained.6setMaxListeners(n)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.7listeners(event)Returns an array of listeners for the specified event.8emit(event, [arg1], [arg2], [...])Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise.For creating a new eventvar event=require(‘events’);var eventEmitter=new event.EventEmitter();For assigning any function to events. So, when this event is fired, the function gets executed.eventEmitter.on(‘eventName’,functionName);For firing the events.eventEmitter.emit(‘eventName’);Example:var?event?=?require('events');??var?eventEmitter?=?new?event.EventEmitter();??console.log('Function?started...');??//??Add?listener?function?for?Sumof2Number?event??evetnEmitter.on('Sumof2Number',?function(num1,?num2)?{??????console.log('Sum?of?both?Number?:?'?+?(Number(num1)?+?Number(num2)));??});??//??Add?listener?function?for?Mulof2Number?event??eventEmitter.on('Mulof2Number',?function(num1,?num2)?{??????console.log('Multiplication?of?both?Number?:?'?+?(Number(num1)?*?Number(num2)));??});??//??Call?or?fire?both?event.??evetnEmitter.emit('Sumof2Number',?'10',?'20');??evetnEmitter.emit('Mulof2Number',?'10',?'20');??console.log('Function?Ended...');?? ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download