Download presentation
Presentation is loading. Please wait.
Published byLinda Bergman Modified over 5 years ago
1
Week 02 http://fog.ccsf.edu/~hyip
Node.js Week 02
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: > 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!
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 >
7
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)
8
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
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. 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. 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 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.
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 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.
25
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.
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 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.