1 / 27

Node.js

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.

apoteet
Download Presentation

Node.js

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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.

  3. 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: c:\nodejs_workspace> node > • To terminate the Node REPL: Press ctrl-c twice.

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

  5. 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! undefined

  6. 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 undefined >

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

  8. REPL Commands

  9. 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)

  10. 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.

  11. 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/

  12. 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.

  13. 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.

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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.

  19. 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.

  20. 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)]

  21. 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.

  22. EventEmitter • EventEmitter class lies in events module. It is accessibly via following syntax: // import events module var events = require ('events'); // create an eventEmitter object vareventEmitter = 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.

  23. 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.

  24. EventEmitter Methods

  25. EventEmitter Methods (continue…)

  26. 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.

  27. 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.

More Related