Week 02 http://fog.ccsf.edu/~hyip Node.js Week 02 http://fog.ccsf.edu/~hyip.

Slides:



Advertisements
Similar presentations
© 2014 IBM Corporation Empowering the IBM ecosystem Introduction to Developing applications using node.js on Bluemix IBM Ecosystem Development Instructors.
Advertisements

CSCI 3100 Tutorial 3 JavaScript & Node.js Presented by SU Yuxin Department of Computer Science and Engineering The Chinese University of Hong Kong 1.
Programming project #4 1 CS502 Spring 2006 Programming Project #4 Web Server CS-502 Operating Systems Spring 2006.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
A First Program Using C#
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Introduction to Shell Script Programming
Node.js - What is Node.js? -
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
Linux Operations and Administration
An Introduction to Front-end Web Development Tom Perkins.
Node.Js 1. 2 Contents About Node.Js Web requirement latest trends Introduction Simple web server creation in Node.Js Dynamic Web pages Dynamic web page.
Node.JS introduction. What is Node.JS? v8 JavaScript runtime Event driven Non-blocking standard libraries Most APIs speak streams Provides a package manager.
Perl Subroutines User Input Perl on linux Forks and Pipes.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Introduction to Node.js® Jitendra Kumar Patel Saturday, January 31, 2015.
Configuring Nodes Application on BlueMix
Node.js Modules Header Mastering Node.js, Part 2 Eric W. Greene
NodeJS and MEAN cs6320.
>> Introduction to JavaScript
Development Environment
Running a Forms Developer Application
Node.Js Server Side Javascript
Chapter Objectives In this chapter, you will learn:
How to link a test to a launcher (in this case a shell launcher)
Node.js Express Web Applications
Web Design II Flat Rock Community Schools
Chapter 2 - Introduction to C Programming
NodeJS and MEAN Prof. L. Grewe.
3 Things Everyone Knows About Node JS That You Don't
The Linux Operating System
Build Better Apps with MEAN.
Node.js Packages Header Mastering Node.js, Part 4 Eric W. Greene
Chapter 2 - Introduction to C Programming
Week#2 Day#1 Java Script Course
The structure of computer programs
Week 05 Node.js.
Week 03 Node.js Week 03
Node.Js Server Side Javascript
Week 04 (Final Project) Node.js Week 04 (Final Project)
Angularjs Interview Questions and Answers By Hope Tutors.
2017, Fall Pusan National University Ki-Joune Li
JavaScript Introduction
Operation System Program 4
NodeJS coding basics L. Grewe.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Topics Introduction to File Input and Output
Chapter 2 - Introduction to C Programming
T. Jumana Abu Shmais – AOU - Riyadh
Web Programming Language
Chapter 2 - Introduction to C Programming
Cordova & Cordova Plugin Installation and Management
INTRODUCTION TO By Stepan Vardanyan.
Week 01 Node.js Week 01
Linux Shell Script Programming
Lecture 5: Functions and Parameters
CS5220 Advanced Topics in Web Programming More Node.js
JavaScript CS 4640 Programming Languages for Web Applications
Lecture 12: The Fetch Api and AJAx
Chapter 2 - Introduction to C Programming
Week 05 Node.js Week 05
Chengyu Sun California State University, Los Angeles
Topics Introduction to File Input and Output
Introduction to C Programming
CS5220 Advanced Topics in Web Programming More Node.js
Chengyu Sun California State University, Los Angeles
JavaScript CS 4640 Programming Languages for Web Applications
Chapter 13: I/O Systems “The two main jobs of a computer are I/O and [CPU] processing. In many cases, the main job is I/O, and the [CPU] processing is.
Presentation transcript:

Week 02 http://fog.ccsf.edu/~hyip Node.js Week 02 http://fog.ccsf.edu/~hyip

Node.js - REPL REPL stands for Read Eval Print Loop. It acts like a window console or UNIX/Linux shell where a command is entered and system responds with an output. Read – Reads user’s input, parse the input into JavaScript data- structure and stores in memory. Eval – Evaluates the data structure. Print – Prints the result. Loop – Loops the above command until user press ctrl-c twice. NOTE: REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes.

How to start the REPL in Node? REPL can be started by simply running node on shell/console without any argument. c:\nodejs_workspace> node You will see the REPL Command prompt: > To terminate the Node REPL: Press ctrl-c twice.

Simple Expression Let’s try to use REPL to perform simple expressions: c:\nodejs_workspace> node > 1 + 3 4 > 1 + (2 * 3) – 4 3 >

REPL variables If var keyword is not used then value is stored in the variable and printed. If var keyword is used then value is stored but not printed. You can use the above variables later. Use console.log to print anything. c:\nodejs_workspace> node > x = 10 10 > var y = 10 undefined > x + y 20 > console.log("Hello World!") Hello World!

Compound Statement (Statement Block) Node REPL supports multiline expression (Compound statement) ({ }). c:\nodejs_workspace> node > var x = 0 undefined > while (x < 3) { … x++; … console.log("x: " + x); … } x: 1 x: 2 x: 3 >

Underscore variable Use _ to get the last result. c:\nodejs_workspace> node > var x = 10 undefined > var y = 20 > x + y 30 > var sum = _ > console.log(sum)

REPL Commands Command Description ctrl + c Terminate the current command ctrl + c twice Terminate the Node REPL ctrl + d up/down keys See command history and modify previous commands tab keys List of current commands .help List of all commends .break Exit from multiline expression .clear .save file_name.js Save current Node REPL session to a file .load file_name.js Load file content in current Node REPL session

Node.js - NPM Node 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)

NPM Global vs Local Installation By default, npm installs any dependency in the local mode. Local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require. Globally installed packages/dependencies are stored in <user- directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any Node.js but can not be imported using require in Node application directly.

NPM Global vs Local (Linux platform) In npm 1.0, there are two ways to install things: globally —- This drops modules in {prefix}/lib/node_modules, and puts executable files in {prefix}/bin, where {prefix} is usually something like /usr/local. It also installs man pages in {prefix}/share/man, if they’re supplied. locally —- This installs your package in the current working directory. Node modules go in ./node_modules, executables go in ./node_modules/.bin/, and man pages aren’t installed at all. https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local- installation/

Global or Local? In general, the rule of thumb is: If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project. If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

When You Cannot Choose You can do one of the following: Install it in both places. (Recommended) Install it globally, and then link the two folders using symbolic links. Then you only need to update the global copy to update all the symlinks as well.

Install express module (local) Install express, a popular web framework using local installation. c:\nodejs_workspace> npm install express Once npm completes the download, you can verify by looking at the content of c:\nodejs_workspace\node_modules Or type the following command: c:\nodejs_workspace> npm ls

Install express module (global) Install express, a popular web framework using global installation. c:\nodejs_workspace> npm install express –g Once npm completes the download, you can verify by looking at the content of <user-directory>/npm/node_modules. NOTE: <user-directory> = c:\Users\my_uid\AppData\Roaming Or type the following command: c:\nodejs_workspace> npm ls -g

Install/uninstall a module Installation of any module is as simple as typing the following command: c:\nodejs_workspace> npm install express Now you can use it in your js file as following: var express = require('express'); Use the following command to uninstall a module: c:\nodejs_workspace> npm uninstall express Note: to verify use the following command: c:\nodejs_workspace> npm ls

Update/search module Use the following command to update a module (run npm update in the same directory as your package.json file): c:\nodejs_workspace> npm update To test the update, run npm outdated. There should not be any results. https://docs.npmjs.com/getting-started/updating-local-packages NOTE: To update all global packages, you can use npm update -g.  Use the following command to search a module: c:\nodejs_workspace> npm search express

Callbacks Concept Callback 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), 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.

How Node Application Work? In Node Application, any asynchronous function accepts a callback as a last parameter and the callback function accepts error as a first parameter. var fs = require("fs"); fs.readFile('./test.txt', function(err, data) { if (err) { console.error(err); return; } console.log(data.toString()); }); console.log("Program Ended"); Here fs.readFile is a async function whose purpose is to read a file. If an error occur during read of file, then err object will contain the corresponding error else data will contain the contents of the file. readFile passes err and data to callback function after file read operation is complete. Note: console.error() will send output to stderr.

Event Loop Overview Node.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)]

Event Driven programming Node.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.

EventEmitter EventEmitter class lies in events module. It is accessibly via following syntax: // import events module var events = require ('events'); // create an eventEmitter object var eventEmitter = new events.EventEmitter(); When an EventEmitter instance faces any error, it emits an ‘error’ event. When 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.

EventEmitter sample var events = require('events'); var eventEmitter = new events.EventEmitter(); var connected = function connected() { console.log('connection successful.'); eventEmitter.emit('data_receive'); } eventEmitter.on('connection', connected); eventEmitter.on('data_receive', function() { console.log('data received successfully.'); }); eventEmitter.emit('connection'); console.log('Program Ended.'); // output connection successful. data_received successfully. Program Ended.

EventEmitter Methods Method Description addListener(event, listener) Adds a listener to the end of the listeners array for the specified event. Returns emitter, so calls can be chained. on(event, listener) once(event, listener) Adds a one time listener for 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. removeListener(event, listener) It 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.

EventEmitter Methods (continue…) Description setMaxListener(n) By default EventEmitter 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. listeners(event) Returns an array of listeners for the specified event. emit(eventName[, arg1][, arg2][,…]) Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each. Returns true if event had listeners, false otherwise.

Node.js Application A node.js application consists of following three important parts: Import required module: use require directive to load a JavaScript module. var http = require('http'); Create server: A server which will listen to client’s request similar to Apache HTTP Server. http.createServer(function (request, response) { response.writeHead(200, { 'Content-Type' : 'text/plain' }); response.end('Hello World!\n'); }).listen(8081); Read request and return response: server created in earlier step will read HTTP request made by client which can be a browser or console and return the response.

References Node.js the Right Way, Jim R. Wilson, The Programatic Bookshelf, ISBN 978-1-937785-73-4 NodeJS: Practical Guide for Beginners, Matthew Gimson, ISBN 978-1- 519354-07-5 Express.js: Node.js Framework for Web Application Development, Daniel Green, ISBN 978-1-530204-06-9 Express.com Tutorials Point The Node Beginner Book, Manuel Kiessling, Leanpub, Link.