-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodeJS- Introduction
More file actions
173 lines (148 loc) · 7.94 KB
/
Copy pathNodeJS- Introduction
File metadata and controls
173 lines (148 loc) · 7.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
1.) What?
Open source, cross platform
Java Script framework for server side web app developement.
Developed on top of Chrome v8 js engine
Helps to directly compile JS into machine code
Its event driven and nonblocking IO to scale
Note:
server side web app developement:
Using scripting languages in server side itself to give customized response for the clients.
Eg: Give custom static web pages to a client from server using scripting languages.
Note:
V8 Engine:
Google's open source, high performance, Javascript and Webassembly engine written in C++. Used by chrome, nodejs etc.
Implements ECMA Script and WebAssembly standards.
Node complies to ECMAScript 262 Spec - standard for scripting languages. Trademark scripting language spec.
2.) Why?
Multithreaded applications faces resource conjuction, cost for scaling etc.
In such case, single threaded application is good, but it have less performance.
NodeJS is based on even loop, event queues and single thread backed with multiple thread pools to over come such issues.
3.) Multi threaded - Single threaded
1-Multiple requests get blocked by listener cum worker - 1-Only one thread called event loop to handle multiple requests
thread
2-Incoming request direct processing model - 2-Queuing and processing model
3-Many context switching - 3-Not much frequent context switching
4-Sync way of doing - 4-Async way of doing (callback etc)
Well suited for distributed systems with huge no: if requests to process
It can manage the problem of allocating same resouce to multiple threads/ request came in
3.) Prominent users?
Netflix, LinkedIn, Uber, ebay, PayPal
4.) Features:
Async & Event driven
All nodejs APIs are non-blocking/ async ie; not waiting for
request -> caller -----request--------> recepient
<----response--------
/<- callback
1.) Very fast due to Chrome v8
2.) Highly scalable due to even driven even after single threading
3.) No buffering, deliver in chucks
5.) Variable Scopes:
Global - in all files available
- Eg: __dirname, __filename
- timer construct - setTimeout(callback, delay) ; setInterval(callback, delay); setImmediate(callback, args)
vs
Local - in single .js file
6.) Callback:
Can be considered as async equivalent of a funcation. It will get executed after a particular task is complete.
Eg: fs.readFile(fname, (err, data)->{});//callback executes after file read
7.) Events:
Node JS is event driven
e = require("events"); - import event module
emitter = new e.EventEmitter(); - create emitter object
emitter.emit('event-name'); - emit event
emitter.on('event-name', ()->{}); - register listener and here, callback is event handler
8.) HTTP:
Uses http module.
Creates a node server in specified port.
Can be server or client
Server:
-------
var http = require('http');
http.createServer().listen(1000); -> enough to start a server. But localhost:1000 will just show as loading because the response stream is not closed.
Then;
http.createServer((req, resp)=>{resp.end()}).listen(1000); -> this won't work until there is a write happens to stream
Then;
http.createServer((req, resp)=>{resp.write("something"); resp.end();}).listen(1000); -> noew works fine.
Client:
-------
const http = require('http');
http.request("http://localhost:1000", (resp)=>{//resp event
resp.on('data', (chunk)=>{
console.log(chunk.toString()); -> if not given toString(), will print byte array ie; buffer
});
}).end(); -> if end() is not given, stream will not be closed and hence nothing happens to server at 1000.
Even console logging given in server didn't work
Server Side with Http Verbs:
----------------------------
var http = require('http');
http.createServer((req, resp)=>{
if(req.url == '/test' && req.method == 'GET'){
resp.write('Hello Kitty');
}else if(req.method == 'POST'){
resp.write('Sending a message....');
}
resp.end();
}).listen(2000);
Client Sending POST Req:
------------------------
var http = require('http');
var options = {"method": "POST", "path" : "http://localhost", "post": "2000"};-> post need to be specified explicitly
http.request(options, (resp)=>{
resp.on('data', (chunk)=>{
console.log(chunk.toString());
});
}).end();
9.) Express:
- Application framework, light weight, used for web-app dev
- Can imagine as abstraction on top of http
- It sets up a routing table internally to dynamically render html pages based on input
Routing:
Defines end points/ URIs for an application.
Routing method:
Methods using http verbs that defines the action to be taken in a particular end point
const express = require('express');
const app = express();//rounte
//app.listen(4000);// Server starts in port 4000. If no port mensioned, application terminates, eventhough no error printing.
//better way
app.listen(4000, ()=>{console.log('started')});-> helful to add a callback at the time of server starting
app.get'/getter', (req, resp)=>{//callback funcation similar for all routing methods
resp.send('message');//no need of write() then end(). This will handing everything.
});
10.)module:
Logical segragation of code.
Each file can be treated as a module.
There is an object module which will be having attributes such as fileName, id, exports etc.
exports holds all items from a module which are to be exposed to others.
So, when we do;
module.exports = something;
and in some other file, when we do, require('module-file'); actually this exported items will be accessible from there.
If we want to expose multiple items from module,
module.exports.item1 = item_1;
module.exorts.item2 = item_2;
can be done.
After requiring;
const mod = require('module-file');
mod.item1 or mod.item2 will allow access.
11.)app.use() vs app.all():
Both are used to add middlewares to be used across given url patterns. Order of deinition is follwed by order of execution.
use() not used regx. But all() can use regx. But now both can support regx from node4.x ownwards.
app.use('/abc', func)- means execute func for all urls /abc, /abc/123 etc.
app.all('/abc', func)- means only for route /abc. Not for /abc/*.
So, app.all('/abc/*') can apply to all routes /abc/xyx, /abc/123 etc but not /abc.
app.all() -> to handle all http method calls. app.all('*', fun1, fun2...). It was not expected to be for middleware. But now with latest node versions, its becoming similar to use().
app.use() -> to add middlewares as callback to the routes. Only one callback funcation allowed. app.use('/', callbackFun);
When all() or use() is used, to end req-res cycle, anyways, req & res args are to be passed into it.
If next() call is not done, it won't proceed.
If req-res cycle not ended, timed waiting comes.
Now, with >4.x, only /app = /app, /app/* for use() but /app is only /app & /app/* is /app/anything for all(). This is the only difference.
12.)const var1 vs const {var1}:
const {var1} is a concept called ES6(EcmaStandard6 = Ecma Script 2015) destructuring assignment
Eg:
var person = {name: 'asha', mark: 90, pass: true, location: 'Bangalore', country: 'India'};
var {name, country} = person;
console.log(name + " from " + country);// will print asha from India
also
var {name: username, country} = person;
console.log(username + " from " + country);// will print asha from India. Here assigned to var username.
That time if we use name instead of username, error comes at runtime that name is not defined.
13.)