/
Week 05 Node.js (Simplified version) Week 05 Node.js (Simplified version)

Week 05 Node.js (Simplified version) - PowerPoint Presentation

isabella2
isabella2 . @isabella2
Follow
66 views
Uploaded On 2023-07-22

Week 05 Node.js (Simplified version) - PPT Presentation

What is Nodejs Nodejs provides a nonblocking architecture using event loop processing based on single threaded JavaScript model and built on top of Googles V8 JavaScript Engine ID: 1009921

event node blocking data node event data blocking function asynchronous console file err log read callback stream loop version

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Week 05 Node.js (Simplified version)" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Week 05Node.js (Simplified version)

2. What is Node.js?Node.js provides a non-blocking architecture using event loop processing based on single threaded JavaScript model and built on top of Google’s V8 JavaScript Engine. Non-blocking execution means asynchronous execution. For any Input or Output (I/O) execution, an I/O event will call the I/O event handler to handle the I/O with callback function. Node.js will not wait for the I/O to complete, and then will execute the next instruction. When the I/O completed, callback function will be called.

3. Event Loop ProcessingEvent loop processing in Node.js is a programming style where the flow of execution is determined by events. Events are handled by event handlers or event callbacks. An event callback is a function that is invoked when something significant happens such as when the result of a database query is available. Therefore, Node.js is an event-driven or asynchronous programming. It’s important to know that event loop in Node.js is just one thread running inside one process, which means that, when an event happens, the event handler can run without interruption. In other words, there is at most one event handler running at any given time and any event handler will run to completion without being interrupted.

4. Node.js BackgroundNode.js was invented in 2009 by Ryan Dahl along with other developers while working at Joyent. The Node.js’ Package Manager (NPM) was introduced in 2011, allowing publishing and sharing node.js source code by the community. Node.js was originally developed for the Linux environment. The first node.js to support Windows was released in July 2011. Node.js went through several technical changes including internal conflict over Joyent’s governance, resulting in Fedor Indutny (Node.js core team developer) starting io.js, a fork of Node.js.

5. Node.js BackgroundIn February 2015, the Node.js foundation was announced, providing the opportunity of merging Node.js and io.js communities together under the Node.js foundation. On 10/12/2015, Node 4.2.0 (LTS) was announced, the first release covered under the new LTS plan (Long Term Support).Node’s core functionalities are kept to a minimum. There are many third-party modules supporting Node.js and can be downloaded, installed, and managed using Node Package Manager (NPM) to expand node’s functionalities.

6. Features of Node.jsAsynchronous and Event Driven: All APIs of Node.js library are asynchronous and non-blocking. Node.js server never waits for an API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.Single-Threaded: Node is a single-threaded environment. At most, only one line of your code will ever be executing at any time. Node I/O tasks are using non-blocking techniques. Rather than waiting line-by-line for an operation to finish, it creates a callback that will be invoked when the operation eventually succeed or fails.

7. Overview of Blocking vs Non-BlockingBlocking is when the executing of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a blocking operation is occurring.Synchronous methods in the Node.js are the most commonly used blocking operations.

8. Overview of Blocking vs Non-BlockingAll of the I/O methods in the Node.js standard library provide asynchronous versions, which are non-blocking, and accept callback functions. Some methods also have blocking counterparts, which have names that end with sync.

9. Comparing CodeBlocking methods execute synchronously and non-blocking methods executes asynchronously.Using the File System modules, this is a synchronous file read (blocking): const fs = require("fs"); const data = fs.readFileSync("/test.txt"); // blocking Here is an equivalent asynchronous example (non-blocking): const fs = require("fs"); fs.readFile("/test.txt", function (err, data) { if(err) throw err; });

10. Blocking vs Non-Blocking codesUsing the File System modules, this is a synchronous file read: const fs = require("fs"); const data = fs.readFileSync("/test.txt"); // blocks until file is read console.log(data); moreWork(); // will run after console.logHere is an equivalent asynchronous example: const fs = require("fs"); fs.readFile("/test.txt", (err, data) => { if(err) throw err; console.log(data); }); moreWork(); // will run before console.log

11. Download and Install Node.jsDownload and install latest version of Node.js Instruction for windows O/S click here (http://fog.ccsf.edu/~hyip/nodejs/week01/note/week_01_install_nodejs_windows.doc).Instruction for Mac O/S click here (http://fog.ccsf.edu/~hyip/nodejs/week01/note/week_01_install_nodejs_mac.doc).Create a working folder (nodejs_workspace).Check the Node.js version that just installed. c:\nodejs_workspace>node --version (or node –v)

12. Node.js - NPMNode Package Manger (NPM) provides two main functionalities:Online repositories for Node.js packages/modules.Command line utility to install packages, do version management and dependency management of Node.js packages. NOTE: NPM comes bundled with Node.js after v0.6.3 version. To verify the NPM version:C:\Nodejs_WorkSpace>npm --version (or npm –v)

13. Callbacks ConceptCallback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task.Node.js makes heavy use of callbacks.For example (non-blocking) readFile(), a function to read a file may start reading file and return the control to execution environment immediately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for file I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

14. Event Loop OverviewNode.js is a single threaded application but it supports concurrency via concept of event and callbacks.As every API of Node.js are asynchronous and being a single thread. It uses asynchronous function calls to maintain the concurrency.Node uses observer pattern (waiting for event).Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the even listener function to get executed.Event Loop process:(1) Load the program – (2) wait for event – (3) handle event – (4) execute callbacks – (5) exit if no more to do or wait for event [repeat from (2)]

15. Event Driven programmingNode.js uses Events heavily and it is also one of the reason why Node.js is pretty fast compared to other similar technologies.As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur.What is the difference between Events and callbacks?The difference lies in the fact that callback functions are called when an asynchronous function returns its result where event handling works on the observer pattern. The functions which listens to events acts as observer. Whenever an event got fired, its listener function starts executing.

16. Node.js - StreamsWhat are Streams?Streams are objects that let you read data from a source or write data to destination in continuous fashion.In Node, there are four types of streams:Readable: stream which is used for read operation.Writable: stream which is used for write operation.Duplex: stream which can be used for both read and write operation.Transform: a type of duplex stream where the output is computed based on input.

17. Piping StreamsPiping streams: Piping is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream.

18. Node.js – Sync & Async Readvar fs = require('fs');// Asynchronous readfs.readFile('./test.txt', function (err, data) { if (err) console.error(err); console.log('Asynchronous read: ' + data.toString());});// Synchronous readvar data = fs.readFileSync('./test.txt');console.log('Synchronous read: ' + data.toString());console.log('Program Ended.');

19. Node.js – Sync & Async Writevar fs = require('fs');var out_data = 'Outdata line 1. \r\nOutdata line 2. \r\nOutdata last line.';// Asynchronous writefs.writeFile('./fs_write_output_async.txt', out_data, function (err) { if (err) console.log(err); console.log('Output Async file content: ' + out_data);});// Synchronous writefs.writeFileSync('./fs_write_output_sync.txt', out_data);console.log('Output Sync file content: ' + out_data);console.log('Program Ended.');