Node Js
Node Js
Node Js
js
What is Node.js?
waiting!
Blocking I/O
Many web applications have code like this, i.e.
I/O request, ...
var result = db.query("select * from T");
// use result
What is the software doing while it queries the
In many cases, just waiting for the response
database?
from the database query! Before it can use the
result.
This is called blocking I/O the software
execution is suspended until the I/O completes.
- Bad news! Wastes time.
Callback function
Example
Multi-Threading
Multi-threading is a language feature found in
many modern programming languages, e.g.
Java, C#.
It allows a software process to spawn a copy (or
a partial copy) of itself.
This works best on multi-core processors.
JavaScript is Event-Driven
Recall how JavaScript works in the browser
- JavaScript registers for events
( onXXX=function() )
- When something (i.e. an event) happens,
JavaScript is invoked
- The browser continues execution when
JavaScript returns from handling the event.
Node.JS takes this approach
- Start an operation via a function call
- Operation defines a set of events tagged by
name
- Register callbacks (i.e. functions) for events
of interest
- Return control to node.js
Summary
In a normal process cycle, a web server, while
processing a client request, will wait for I/O
operations to complete, and thus blocks the next
request to be processed.
Node.js, on the other hand, processes each
request as an event.
The server does not wait for an I/O operation
to complete while it can handle other request at
the same time.
When any I/O operation of a request is complete,
it will call-back the server to complete the
request.
Single thread
Is also
Synchrono
us
Multiple connections
multithreaded
Asynchronous
Asynchronous
Asynchronous
Scaling node.js
Requires running multiple node.js servers
- On the same machine (multiple cores)
- On separate machines (cluster)
And sending requests based on incoming IP
address
Can be done using node.js
Example
var http = require('http');
http.createServer( function (req, res) {
res.writeHead(200, {'ContentType':'text/plain'});
res.end('Hello, World!');
}).listen(8080,'127.0.0.1');
Request Wrapper
The Request wrapper
http.IncomingMessage class
Implements the Readable Stream interface
Properties
httpVersion '1.1' or '1.0'
headers object for request headers
method 'GET', 'POST', etc.
url the URL of the request
Response wrapper
The Response wrapper
Implements the Writable Stream interface
Methods
writeHead(statusCode, [headers])
write(chunk, [encoding])
end()
Always call the methods in the following way
writeHead()
write()
end()