Top Banner
Complete Guide On Node.js By: Senior Developer Prabin Silwal
112

A complete guide to Node.js

May 10, 2015

Download

Education

Prabin Silwal

A complete guide to start server side javascript programming called Node.js by Er. Prabin Silwal.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: A complete guide to Node.js

Complete Guide On Node.js

By: Senior DeveloperPrabin Silwal

Page 2: A complete guide to Node.js

What you should know before?

JavascriptUnix command

Page 3: A complete guide to Node.js

Installation:3way to install

• 1st way: Nodejs.org :– You can download pre-compiled binary– Easy installation– Automatic configured environment– But, updates require reinstallation– And switching versions need reinstallation

Page 4: A complete guide to Node.js

2nd way : Version manager(nvm):Install any version quicklySwitch version quicklyEasy install on LinuxBut no widzard based installation(must use

command line interface)And reinstall global modules when switching versionInstall version manager then node

Page 5: A complete guide to Node.js

3rd way : Compile it from source(node)Get absolute new nodeCustomize your installationBut you must be familiar with compiling processAnd takes longerAnd not easy to switch

Page 6: A complete guide to Node.js

Which is preferable?

• For mine 2nd way

Page 7: A complete guide to Node.js

Window installation:

• Download node.js• Click install

Page 8: A complete guide to Node.js

Checking after installation?

• Run command• Type “node” and hit enter• Type “console.log(‘your text’)”

Page 9: A complete guide to Node.js

Note that previous installation process needs re installation for new updates.

Page 10: A complete guide to Node.js

Installing using nvm in Linux(Not wizard mode for Linux):

Page 11: A complete guide to Node.js

Make ready to install by following command:

• sudo apt-get install git• sudo apt-get install curl

Page 12: A complete guide to Node.js

Install using command:

Page 13: A complete guide to Node.js

Why node.js ?

• It is js with browser• JS for both front end and backend (eg: using

jquery)• Native support• It’s fast because it’s mostly C code

Page 14: A complete guide to Node.js

What can you build?

• Websocket server ( Like chat server)• Fast file upload client• Ad server• Any Real- Time Data Apps

Page 15: A complete guide to Node.js

What is Node.js not:

• Web framework• For Beginners (it’s very low level)• Multi- threaded (You can think of it as a single

threaded server)

Page 16: A complete guide to Node.js

Few variables you are familiar about web browser:

• window : (Type in console of chrome)The window object have functions and attributes that have to do something with window being drawn in screen.

Page 17: A complete guide to Node.js

• location: (Type in console of chrome)The location object has all the information about url

that being loaded.

Page 18: A complete guide to Node.js

• document : (Type in console of chrome)The document object contains all oh html displayed

in page

Page 19: A complete guide to Node.js

Now type in node console:• It displays undefined message

Page 20: A complete guide to Node.js

Why not work in node?

• Because node is not just an instance , so “global” is defined in node but not in chrome console where you can get instance version of global object called window.

Page 21: A complete guide to Node.js

• This global object has several functions (which are not in chrome console)

• EG: require function: used to pull in different javascript script files from your appliction

Page 22: A complete guide to Node.js

But error in chrome console:

Page 23: A complete guide to Node.js

Some works on both:

• Eg: console

Page 24: A complete guide to Node.js

Note: local variable vs global

• Eg:name = prabin; //globalVar name = prabin; //local

Page 25: A complete guide to Node.js

Node is Non-blocking: Blocking vs No-blocking 1

Page 26: A complete guide to Node.js

Blocking vs No-blocking 2

Page 27: A complete guide to Node.js

Blocking vs No-blocking 3

Page 28: A complete guide to Node.js

Callback alternate syntax:

Page 29: A complete guide to Node.js

MODULES

Page 30: A complete guide to Node.js

REQUIRING MODULES

var http = require('http'); //http.jsva r fs = require('fs'); // fs.js

How does ‘require’ return the libraries?How does it find these files?

Page 31: A complete guide to Node.js

Custom Module Example:• Prabin_App(base folder)

– Example.jsvar say = require(‘./say_hello_module.js’); //say is assigned as object & has 2 properties : softly

and loudly which both are functionssay.softly(‘prabin’);Say.loudly(‘PRABIN’);

– Say_hello_module(Module Folder)• index.js var hello = function (message){

console.log(‘say hello:’+message);});exports.slowly = hello;//we first declare hello as function and setting slowly to be value of helloexports.loudly = function(message){

console.log(‘SAY HELLO:’+message);});

Page 32: A complete guide to Node.js

LETS CREATE OUR OWN MODULE

Page 33: A complete guide to Node.js
Page 34: A complete guide to Node.js
Page 35: A complete guide to Node.js
Page 36: A complete guide to Node.js
Page 37: A complete guide to Node.js
Page 38: A complete guide to Node.js

• For finding modules:

Page 39: A complete guide to Node.js

NPM: THE USERLAND SEA

“Core” is small. “Userland” is large.

Package manager for node• Comes with node• Module Repository• Dependency Management• Easily publish modules• “Local Only”

Page 40: A complete guide to Node.js

INSTALLING A NPM MODULE

/Home/my_app• $ npm install request https://github.com/mikeal/requestInstalls into local node_modules directory---------------after installation-------------------------------Home/my_app/node_modules/request

----For require/using in your app------------------------------------ /Home/my_app/app.jsva r request = require('request');//Loads from local

node_modules directory

Page 41: A complete guide to Node.js

LOCAL VS GLOBAL MODULE

• Install modules with executables globally:$ npm install coffee-script –g //global$ coffee app.coffee

Note: Global npm modules can’t be required

$ npm install coffee-script //Install locally

Page 42: A complete guide to Node.js

FINDING MODULES

• From npm command line: $ npm search module_nameEg: $ npm search request

Page 43: A complete guide to Node.js

DEFINING YOUR DEPENDENCIESmy_app/package.json{"name": "My App","version": "1","dependencies":

{"connect": "1.8.7"

}}

Then: $ npm install will installs it into the node_modules directoryi.e. my_app/node_modules/connect

Page 44: A complete guide to Node.js

• SEMANTIC VERSIONING:Major Minor Patch 1 . 8 . 7

Page 45: A complete guide to Node.js

Test Time

Page 46: A complete guide to Node.js

NODE.JS : Hello world

Hello.jsvar http = require('http');http.createServer(function(request, response) {response.writeHead(200); //Status code in browserresponse.write("Hello World.");//ResponseTextresponse.end();//Close the connection}).listen(8080);//Listen for connection on this portconsole.log('Listening on port 8080...');

Page 47: A complete guide to Node.js

• Run the server:$ node Hello.js(Listening on port 8080...)

• View output$ curl http://localhost:8080(Hello World)

Page 48: A complete guide to Node.js

Event Loops 1

Page 49: A complete guide to Node.js

Event Loops 2

Page 50: A complete guide to Node.js

Long Running Process

var http = require('http');http.createServer(function(request, response) {

response.writeHead(200);response.write(“Hello World running.");response.end();setTimeout(function() //Represent long running process{

response.write(" Hello World is done.");response.end();

}, 5000); //5000ms = 5 seconds}).listen(8080);

Page 51: A complete guide to Node.js

TWO CALLBACKS HERE

var http = require('http');http.createServer(function(request, response) {

response.writeHead(200);response.write(“Hello World running.");response.end();setTimeout(function() //Represent long running process{

response.write(" Hello World is done.");response.end();

}, 5000); //5000ms = 5 seconds}).listen(8080);

request

timeout

Page 52: A complete guide to Node.js

TWO CALLBACKS TIMELINE

Page 53: A complete guide to Node.js

(With blocking timeline)

Page 54: A complete guide to Node.js

NOTE: TYPICAL BLOCKING THINGS

• Calls out to web services• Reads/Writes on the Database• Calls to extensions

Page 55: A complete guide to Node.js

EVENTS IN THE DOM

• The DOM triggers Events you can listen for those events

Page 56: A complete guide to Node.js

EVENTS IN NODE 1

• Many objects in Node emit events

Page 57: A complete guide to Node.js

EVENTS IN NODE 2

Page 58: A complete guide to Node.js

Also there is custom EventEmitter

var EventEmitter = require('events').EventEmitter;

Page 59: A complete guide to Node.js

var http = require('http');

http.createServer(function(request, response){ ... });

But what is really going on here?http://nodejs.org/api/

Page 60: A complete guide to Node.js

Breaking It downvar http = require('http');

Page 61: A complete guide to Node.js

ALTERNATE SYNTAX

Page 62: A complete guide to Node.js

Streams

Page 63: A complete guide to Node.js

STREAMING RESPONSE

http.createServer(function(request, response) {response.writeHead(200);response.write(“Hello World Writing.");

setTimeout(function() {

response.write(" Hello World is done.");response.end();

}, 5000);}).listen(8080);

Readable stream Writable stream

Output to client: Hello World Writing. (5 seconds later) Hello World is done.

Page 64: A complete guide to Node.js

HOW TO READ FROM THE REQUEST?

Page 65: A complete guide to Node.js

$ curl -d 'hello' http://localhost:8080Output on client: hello

Page 66: A complete guide to Node.js

READING AND WRITING A FILE

var fs = require('fs'); // require filesystem modulevar file = fs.createReadStream("readme.md");var newFile =

fs.createWriteStream("readme_copy.md");require filesystem modulefile.pipe(newFile);

Page 67: A complete guide to Node.js

UPLOAD A FILEvar fs = require('fs');var http = require('http');http.createServer(function(request, response) {var newFile =

fs.createWriteStream("readme_copy.md"); request.on('end', function() { response.end('uploaded!');});

}).listen(8080);On Client:$ curl --upload-file readme.md http://localhost:8080Output on client: uploaded!

Page 68: A complete guide to Node.js
Page 69: A complete guide to Node.js
Page 70: A complete guide to Node.js
Page 71: A complete guide to Node.js
Page 72: A complete guide to Node.js

DOCUMENTATION http://nodejs.org/api/

Page 73: A complete guide to Node.js

REMEMBER THIS CODE 1?

var fs = require('fs');var newFile = fs.createWriteStream("readme_copy.md");var http = require('http');http.createServer(function(request, response) {

request.pipe(newFile);request.on('end', function() {

response.end('uploaded!');});

}).listen(8080);

Page 74: A complete guide to Node.js

REMEMBER THIS CODE 2?http.createServer(function(request, response) {var newFile = fs.createWriteStream("readme_copy.md");var fileBytes = request.headers['content-length'];var uploadedBytes = 0;request.pipe(newFile);request.on('data', function(chunk) {

uploadedBytes += chunk.length;var progress = (uploadedBytes / fileBytes) * 100;response.write("progress: " + parseInt(progress, 10) + "%\n");

});

}).listen(8080);

Page 75: A complete guide to Node.js

Express

Page 76: A complete guide to Node.js

Express

Page 77: A complete guide to Node.js
Page 78: A complete guide to Node.js
Page 79: A complete guide to Node.js
Page 80: A complete guide to Node.js
Page 81: A complete guide to Node.js

SOCKET.IO

Page 82: A complete guide to Node.js

SOCKET.IO

• Traditional

Page 83: A complete guide to Node.js
Page 84: A complete guide to Node.js
Page 85: A complete guide to Node.js
Page 86: A complete guide to Node.js
Page 87: A complete guide to Node.js
Page 88: A complete guide to Node.js
Page 89: A complete guide to Node.js
Page 90: A complete guide to Node.js
Page 91: A complete guide to Node.js

Persisting Data

Page 92: A complete guide to Node.js

Persisting Data

Page 93: A complete guide to Node.js
Page 94: A complete guide to Node.js
Page 95: A complete guide to Node.js
Page 96: A complete guide to Node.js
Page 97: A complete guide to Node.js
Page 98: A complete guide to Node.js
Page 99: A complete guide to Node.js
Page 100: A complete guide to Node.js
Page 101: A complete guide to Node.js
Page 102: A complete guide to Node.js
Page 103: A complete guide to Node.js
Page 104: A complete guide to Node.js
Page 105: A complete guide to Node.js
Page 106: A complete guide to Node.js
Page 107: A complete guide to Node.js
Page 108: A complete guide to Node.js
Page 109: A complete guide to Node.js
Page 110: A complete guide to Node.js
Page 111: A complete guide to Node.js

References:

• IN T R O T O N O D E . J S (Authorized site)• Ihrig C. J. - Pro Node.js for Developers• Gackenheimer C. - Node.js Recipes

Page 112: A complete guide to Node.js

Thank You

• Any Suggestions and queries :Website: http://prabinsilwal.com.npEmail: [email protected]