Download presentation
Presentation is loading. Please wait.
Published byDewi Tanudjaja Modified over 6 years ago
1
Week 01 http://fog.ccsf.edu/~hyip
Node.js Week 01
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. Event 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. This means the current process will not block when it is doing I/O. Therefore, several I/O operations can occur in parallel, and each respective callback function will be invoked when the operation finishes. 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. 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. In a traditional server model, the web applications serving concurrent requests are implemented by using the thread pool model to handle incoming requests by assigning each incoming request to a separate thread of execution. In contrast, event model utilizes a single thread to process events, such as incoming requests from a queue.
3
Node.js background Node.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 developer) starting io.js, a fork of Node.js. In 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 (LTS) was announced, the first release covered under the new LTS plan (Long Term Support).
4
Features of Node.js Asynchronous 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 and Highly Parallel: Other systems try to gain parallelism by running lots of code at the same time, typically by spawning many threads. But not Node.js, Node is a single-threaded environment. At most, only one line of your code will ever be executing at any time. Node gets away with this by doing most I/O tasks using non-blocking techniques. Rather than waiting line-by-line for an operation to finish, you create a callback that will be invoked when the operation eventually succeed or fails.
5
Overview of Blocking vs Non-Blocking
Blocking 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. (Native modules may also have blocking methods) All 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.
6
Comparing Code Blocking methods execute synchronously and non-blocking methods executes asynchronously. Using the File System modules, this is a synchronous file read: const fs = require("fs"); const data = fs.readFileSync("/test.txt"); // blocks here until file is read Here is an equivalent asynchronous example: fs.readFile("/test.txt", function (err, data) { if(err) throw err; });
7
Blocking vs Non-Blocking codes
Using the File System modules, this is a synchronous file read: const fs = require("fs"); const data = fs.readFileSync("/test.txt"); // blocks here until file is read console.log(data); moreWork(); // will run after console.log Here is an equivalent asynchronous example: fs.readFile("/test.txt", (err, data) => { if(err) throw err; }); moreWork(); // will run before console.log
8
Download and install Node.js
Download and install latest version of Node.js Instruction for windows O/S click here ( dows.doc). Instruction for Mac O/S click here ( c.doc). Create a working folder (nodejs_workspace). Check the Node.js version that just installed. c:\nodejs_workspace>node --version (or node –v)
9
Verify Installation Create a js file named hello_world.js in c:\nodejs_workspace with the following statement: console.log("Hello world!"); Now run the hello_world.js: C:\nodejs_workspace>node hello_world.js Verify the Output: Hello World!
10
JavaScript Language (review)
Data types: 3 primitive data types (number, string, boolean). Composite Data Type: Object and Array. Special values: null, undefined, NaN, Infinity. Variables: first character can be letter or underscore, subsequent characters can be letter, number, or underscore. (No space, no reserved words). To define a variable: var name_of_var; Statement is ended with semicolon (;). var a = ;
11
JavaScript Language (review)
Expression will evaluate to a single value with single data type. var a = 3 + 4; // is an expression, and will evulate to 7 (data type is number) Single line comment: // end with new line character \n Multiple line comment: /* start here second line */ Operators: Unary operator (one operand): -88, count++, !flag Binary operator (two operands): , num1 < num2 Ternary operator (three operands): (condition) ? True expression : False expression ;
12
JavaScript Language (review)
5 categories of operators: String operators: +, += Arithmetic operators: +, -, *, /, %, ++, -- Assignment operators: =, +=, -=, *=, /=, %= Comparison operators: ==, !==, >, >=, <, <=, (automatic data type conversion) === (equivalent), !=== (not equivalent) (No automatic data type conversion) Logical operators: &&, ||, ! Conditional Operator: var age = 16; (age < 18)? var answer="Minor" : var answer="Adult";
13
JavaScript Language (review)
Special operators: delete (delete array entry or object) new (use to create new object) this (refer to current object) void (tell JavaScript to evaluate an expression and returns no value)
14
The order of operations
() . [] new function() ! void delete * / % + - < <= > >= == != === !== && || Conditional Operator = += -= *= /= %=
15
JavaScript Functions Function declaration: function function_name () {
} Invoke function: function_name(); Passing parameters/arguments to function: function function_name(fname) { function_name("My Name"); Returning data/value from function: function function_name(a, b) { return a + b;
16
JavaScript selection If statement: if (condition) { // true statements
} else { // false statements } If else if statement: if (condition) { // if condition is true } else if (cond2) { // if cond2 is true } else { // catch all statement
17
JavaScript switch statement
switch (expression) { case label1: // statements break; case label2: default: //statements; }
18
JavaScript Loops JavaScript for loop: for (var i=0; i < 3; i++) {
// statements; } JavaScript while loop: var i = 0; while (i < 3) { i++;
19
JavaScript do while loop
var i = 0; do { // statements; i++; } while(i < 3); NOTE: special statements: break; // get out of inner loop continue; // go to testing and repeat the loop
20
JavaScript Arrays Create JavaScript Array:
var js_ary = ["John", "Doe"]; OR var js_ary = new Array(); js_ary[0] = "John"; js_ary[1] = "Doe";
21
JavaScript Objects Dot notation: object_name.property_name
object_name.method_name(parameter, argument); Create JavaScript Object: var js_obj = { firstName : "John", lastName : "Doe" }; OR var js_obj = new Object(); js_obj.firstName = "John"; js_obj.lastName = "Doe“;
22
References Node.js the Right Way, Jim R. Wilson, The Programatic Bookshelf, ISBN NodeJS: Practical Guide for Beginners, Matthew Gimson, ISBN Express.js: Node.js Framework for Web Application Development, Daniel Green, ISBN Express.com Tutorials Point The Node Beginner Book, Manuel Kiessling, Leanpub, Link.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.